dqjo4340 2015-05-09 18:34
浏览 48
已采纳

在没有JQuery的情况下通过Ajax / JSON发送数组

I'm experimenting with Ajax and am trying to send a 1-dimensional, non associative array from a PHP function to a calling javascript function. The array is simple stuff like:

$arr[0] = 1900-1905
$arr[1] = 1905-1911

etc. For various reasons I'm using jQuery, but I am reasonably familiar with the raw Javascript way of using Ajax but I can't seem to find a way how to process the JSON data client side using Javascript. I'm going to be calling the PHP function using a call to something like

myserver.com/myfunction.php?var1=1&var2=2&var3=3

and I know you have to use echo json_encode($arr) in the PHP function, but what do you do in the Ajax method to convert the JSON back into an array, and access the array elements? From reading some of the answers on this forum, this is the part where people fall at the hurdle.

Many thanks.

  • 写回答

2条回答 默认 最新

  • douyi6290 2015-05-09 18:46
    关注

    Try This

    function callAjax()
    {
    var xmlhttp;
    if (window.XMLHttpRequest)
      {
      xmlhttp=new XMLHttpRequest();
      }
    else
      {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) //Success
        {
            var objResponse = JSON.parse(xmlhttp.responseText); //JSON.parse Parses a string as JSON
            console.log(objResponse[0]); //1900-1905
        }
      }
    xmlhttp.open("GET","myserver.com/myfunction.php?var1=1&var2=2&var3=3",true);
    xmlhttp.send();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!