【问题标题】:How to access the data in the object returned by an ajax call [duplicate]如何访问ajax调用返回的对象中的数据[重复]
【发布时间】:2014-10-13 00:18:27
【问题描述】:

我发出一个 AJAX 请求:

   function getdbsite(wantedid) {
      alert(wantedid);
      $.ajax({
         url: 'public/xml/xml_getdbsite.php',
         dataType: 'text',
         data: {"wantedid": wantedid},
         type: 'POST',
         success: function (data) {
            resultObj = eval(data);
            site=resultObj[0];
           // alert(site->language);  }These cause errors
           // alert(site->name);      }
            reply=resultObj[1];
         }
      });
   }

服务器端PHP:

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once '../../includes/initialize.php';
header("Content-Type: application/json");
$id=$_POST['wantedid'];
$site = Website::find_by_id($id);
if($site){
   $arr[0] = $site;
   $arr[1] = "OK";
}else {
   $arr[0] = "$id";
   $arr[1] = "Failed";
}
$arr = json_encode($arr);
echo("$arr");

AJAX 响应:[{"id":"19","idlanguage":"1","name":"QI"},"OK"]

但我无法访问数据库行。

我已经搜索并发现: Parse PHP array of objects with jQuery Ajax

但不明白答案,他们的例子只有1个字段。请帮忙。

【问题讨论】:

  • dataType: 'text', json dataType,jquery 已经可以将json 字符串转换成一个对象了
  • alert(site-&gt;language); }These cause errors -> 运算符。

标签: javascript php jquery ajax


【解决方案1】:

我强烈建议不要为此使用eval() 函数。

相反,明确设置您将从服务器接收 JSON:

dataType: 'JSON',

例子:

PHP:

if($site){
   $arr['data'] = $site;
   $arr['message'] = "OK";
}else {
   $arr['data'] = $id;
   $arr['message'] = "Failed";
}

echo json_encode($arr);
exit;

JS:

$.ajax({
    url: 'public/xml/xml_getdbsite.php',
    dataType: 'JSON',
    data: {"wantedid": wantedid},
    type: 'POST',
    success: function(response) {

        // use dot notation not -> arrow notation
        var data = response.data;
        var message = response.message;
        alert(message);

        alert(data.id);
        alert(data.idlanguage);

    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 2020-08-14
    • 1970-01-01
    • 2011-03-29
    • 2011-07-06
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多