解码从ajax返回的javascript中的json对象

时间:2015-04-15 02:25:48

标签: javascript php jquery ajax json

我已经在php中准备了一个数组,用json_encode返回ajax。当通过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对象环境变量中?感谢。

2 个答案:

答案 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"
});

此处有更多详情:https://api.jquery.com/jquery.post/