我已经在php中准备了一个数组,用json_encode返回ajax。当通过ajax返回时,它的行为不符合我的预期。
$.ajax({
url:"dbpaginate.php",
type:"POST",
data: {'environmentvars': tmp},
cache: false,
success: function(response){
alert('Returned from ajax: ' + response);
alert(response["actionfunction"]);
$j.each(response, function (index,element) {
alert(index);
alert(element);
});
});
Returned from ajax: array(5) {
["actionfunction"]=>
string(8) "showData"
["sortparam"]=>
string(6) "ticker"
["sortorder"]=>
string(3) "ASC"
["page"]=>
int(1)
["htmlstring"]=>
string(0) ""
}
{"actionfunction":"showData","sortparam":"ticker","sortorder":"ASC","page":1,"htmlstring":"","htmltext":"<table id=\"summaryheader\"> [...lots of html...]<\/div>\n"}
undefined
showData
如何有效地将我的json response
移植到javascript对象环境变量中?感谢。
答案 0 :(得分:2)
您必须使响应有效JSON。您的服务器端脚本中的某个地方似乎有print_r
语句,其输出包含在响应中。删除它。
响应总是文本,即JavaScript中的字符串
。您可以在处理数据之前解析JSON(Parse JSON in JavaScript?)或告诉jQuery为您解析它,方法是添加dataType: 'json'
选项。
答案 1 :(得分:0)
您应该在这些方法中指定一个dataType参数,该参数主要用于声明您希望从服务器获得的数据类型。
以下是一个例子:
$.ajax({
type: "POST",
url: <your-request-url>,
data: <your-data>,
success: function(){ ... },
dataType: "json"
});