0

我有以下 Jquery 电话。

$("#btnfindAddress").click(function() {
   var dataString = '';
        //built the data string that will be sent with ajax
        dataString += 'business_name='+$('#company').val()+'&';
        dataString += 'business_city='+$('#city').val()+'&';
        dataString += 'business_country='+$('#country').val()+'&';
        dataString += 'business_zipcode='+$('#zipcode').val();
$.ajax({
type: "GET",
url: "/locations/search",
contentType: "application/text; charset=utf-8",
data: dataString, 
success: function(data){ 
    var text_result="";
    text_result="<table  id=\"thetable\"><tbody>";
    $.each(data,function(index,value){
          text_result+="<tr>";
          text_result+="<td>"+value.name+"</td>";
          text_result+="<td>"+value.address+"</td>";
          text_result+="<td>"+value.zipcode+"</td>";
          text_result+="<td><a name="+ value.name+" address="+value.address+" city="+value.city+"href=>Select</a></td>";
          text_result+="</tr>";
    });
          $('#locations').html(text_result);
}
});
 return false; 
});

它生成以下html

<a href="" angeles="" city="Los" website="null" zipcode="90007"  st="" hoover="" s="" address="3303" coffee="" name="Starbucks">Select</a>

这些值按空格分隔。

应该是

    <a href="" city="Los angeles"   address="3303 S Hoover st" coffee="" name="Starbucks">Select</a>

我怎样才能解决这个问题 ?

谢谢

4

2 回答 2

3

您需要在生成的 html 中添加引号:

text_result+="<td><a name=\""+ value.name+"\" address=\""+value.address+"\" city=\""+value.city+"\" href>Select</a></td>";
于 2012-12-30T18:54:54.900 回答
1

您不应该使用字符串操作来执行此操作。如果您执行以下操作,jQuery 会正确处理编码...

var $table = $('<table>').attr('id','theTable');
$.each(data,function(index,value) {
    $table.append(
       $('<tr>')
         .append($('<td>').text(value.name))
         .append($('<td>').text(value.address))
         .append($('<td>').text(value.zipcode))
         .append($('<td>').append(
           $('<a>').attr('name',value.name).attr('address',value.address)
         )
    );
});
$('#locations').html($('<div>').append($table).html());

更好的是使用 EJS 或 Moustache 之类的模板方法。

于 2012-12-30T19:03:33.957 回答