如何访问在 ajax 中返回的结果数组

How to access result array returned in ajax?

本文关键字:返回 结果 数组 ajax 何访问 访问      更新时间:2023-09-26

Arg!!我完美地工作了,现在我又回到了用头撞键盘。

我想访问数组中定义的列,但我没有得到定义,但是如果我使用警报显示结果,如下面的代码截图中所述,我会看到以下内容:

[{"firstname":" Mr","0":" Mr","lastname":" Two","1":" Two","user_public_info_id":"3","2":"3","st_usage_id":null,"3":null},{"firstname":" Mr","0":" Mr","lastname":" Three","1":" Three","user_public_info_id":"5","2":"5","st_usage_id":null,"3":null}] 
*** 
g 
*** 
e 
*** 
undefined

这是 Ajax 代码:

$.ajax({
 type: "POST",
 url: "models/ajaxHandler.php",
 data: "handler=getStActivitySharingList&stu_id="+stu_id,
 datatype: "json",
 success: function(result){
    var count = 0;
    if (result !== null)
    {
       //display results
       alert(result + " <br />*** <br />" + result[0] +" <br />*** <br />" + result[1] + " <br />*** <br />"  + result[0]["firstname"]);
       //clears choice list
       clearOptions();
       //result = $.parseJSON(result); //if this is used cannot display result again
       alert (result);   
       $.each(result, function (i, elem) {
           alert("elem"+elem.st_usage_id );    //displays as undefined and won't break
           if (elem.st_usage_id === null)
           {
               count++;
               alert(elem.firstname + " "+ elem.lastname + " " + elem.user_public_info_id);
               appendOption(elem);
           }
       });              
     }
     alert(count);
     if (count === 0){
         noResultsAvailableOption();
     }else{
        resultsAvailableOption();
      }
        ShowDialog(false);
        e.preventDefault();
      },
      error: function(){
           alert("ajax failure: could not retrieve a list of contacts");
      }
  });
我不知道

你是如何从PHP返回它的,但是在jquery中尝试:

sucess: function (result)
{
    console.log(JSON.parse(result)); // parse string to json
}

见 json.org

为了更好地回答这个问题,就是实现更好的调试过程。

这是我用于调试此问题的代码。xmlHttpRequest 的分解清楚地向我表明问题出在数据上,并且在尝试将数据编码为 json 时遇到了非法字符异常。

解决任何问题的一个好方法是首先实现正确的调试过程,其他一切都会自行解决。

error: function(xmlHttpRequest, status, error){
    alert("ajax failure: could not populate list of countires | " + status + " | error:" + error);
    var xmlHttpRequestStr= "";
    for(x in xmlHttpRequest)
         xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
    alert(xmlHttpRequest);
}