在没有JQuery的情况下通过Ajax/JSON发送数组 [英] Sending Arrays via Ajax/JSON without JQuery

查看:72
本文介绍了在没有JQuery的情况下通过Ajax/JSON发送数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Ajax,并试图将一维非关联数组从PHP函数发送到调用javascript函数.数组是简单的东西,例如:

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

等 由于各种原因,我正在使用jQuery,但是我相当熟悉使用Ajax的原始Javascript方式,但是我似乎找不到找到使用Javascript处理JSON数据客户端的方法.我将使用对类似

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

,我知道您必须在PHP函数中使用echo json_encode($ arr),但是您如何在Ajax方法中将JSON转换回数组并访问数组元素呢?通过阅读该论坛上的一些答案,这是人们陷入困境的部分.

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.

非常感谢.

推荐答案

尝试一下

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();
}

这篇关于在没有JQuery的情况下通过Ajax/JSON发送数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆