【问题标题】:access elements of an ajax response comes as a stirng of arrayajax 响应的访问元素以数组字符串的形式出现
【发布时间】:2016-04-05 06:37:12
【问题描述】:

我已向我的服务器请求用户提交的帖子列表。但作为响应,我得到一个包含 stdClass 对象数组的字符串。如果它是实际数组,那不会是问题。但它是一个刺痛。像下面这样:

   " array(
      [0]=>stdClass('title'='title of post','post_id'=4),
      [1]=>stdClass('title'='title of post','post_id'=4)
    )"

typeof(response) 给了我“字符串”。我的问题是,我如何才能从中访问单个元素? 代码:

$.ajax('../includes/ajaxpostinfo.php',{
    data:data,
    type:"POST",
    success:function(response){

        alert(typeof(response)); // it prints out "string"


        },
    error:function(response){
          alert(response);
       }
});

【问题讨论】:

  • 复制您的ajaxpostinfo.php 代码。
  • 您需要使用 PHP API 中的return json_encode(responseArray);。不是var_dump它。

标签: javascript php jquery arrays ajax


【解决方案1】:

也许如果你添加

dataType : "json"

在你的 ajax 请求中

“json”:将响应评估为 JSON 并返回一个 JavaScript 对象。除非请求在其请求选项中包含 jsonp: false ,否则跨域“json”请求将转换为“jsonp”。 JSON数据被严格解析;任何格式错误的 JSON 都会被拒绝并引发解析错误。从 jQuery 1.9 开始,空响应也会被拒绝;服务器应该返回 null 或 {} 的响应。 (有关正确的 JSON 格式的更多信息,请参阅 json.org。)

JQuery Ajax documentation

【讨论】:

  • 数据类型应该从响应的 MIME 类型中推断出来,但它也应该添加到 AJAX 调用中。很好的建议,但不要认为它会解决问题。
【解决方案2】:

做一些这样的事情:

服务器:

$array= array(
      [0]=>stdClass('title'='title of post','post_id'=4),
      [1]=>stdClass('title'='title of post','post_id'=4)
    );
echo json_encode($array);

客户:

$.ajax('../includes/ajaxpostinfo.php',{
    data:data,
    type:"POST",
    dataType : "json",//set data type
    success:function(response){

        alert(typeof(response)); 


        },
    error:function(response){
          alert(response);
       }
});

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2014-05-27
    • 2021-05-31
    • 2022-06-17
    相关资源
    最近更新 更多