【问题标题】:Sending an array using javascript ajax使用 javascript ajax 发送数组
【发布时间】:2012-08-24 15:09:44
【问题描述】:

在 jquery 中我可以做到这一点

myAray=['abc', '123', 'more'];
$.post('myscript.php', {data:myAray}, function(data){
    alert(data);
});

如何使用纯 javascript 做同样的事情?我想使用 POST 方法将数组发送到我的 php 脚本。我找到了很多例子,但都是与 jquery 相关的。

提前致谢。

【问题讨论】:

标签: javascript ajax


【解决方案1】:

您必须使用XMLHttpRequest 并自己序列化数组:

function ajax(myArray) {

    var xmlHTTP;

    if (window.XMLHttpRequest) { 
        xmlHTTP = new XMLHttpRequest();
    } else { 
        xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHTTP.onreadystatechange = function () {
        if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
            // do whatever it is you want to do
        }
    }

    //Serialize the data
    var queryString = "";
    for(var i = 0; i < myArray.length; i++) {
        queryString += "myArray=" + myArray[i];

        //Append an & except after the last element
        if(i < myArray.length - 1) {
           queryString += "&";
        }
    }

    xmlHTTP.open("POST", "www.myurl.com", true);
    xmlHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    xmlHTTP.send(queryString);
}

【讨论】:

  • 我可以在 $_POST['data'] 中得到这个
  • 我想它会出现在$_POST['myArray'] 下。您可以将 for 循环中的字符串更改为 "data=" + myArray[i];,它应该显示在 $_POST['data']
  • 这里的queryString 是什么?我觉得应该是data
  • @user2567857:不要对改变原意的帖子进行编辑。评论就足够了。
  • @staticx 取决于 OP。此答案已被接受,因此用户可能不会阅读 cmets。
【解决方案2】:

搞砸这个。

JS

var myarray = Array("test","boom","monkey");
send("test.php", myarray);  

function send(url, data)  
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        console.log(xhr.responseText);
    }
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("data= " +data);
}

PHP

<?php 
$array = explode(',', $_POST["data"]);

for($i=0,$l=count($array); $i<$l; $i++) 
{
echo $array[$i].'<br>';
}
?>

【讨论】:

  • 很高兴知道为什么我的回答被否决了。我们都在这里学习!
【解决方案3】:
function loadXMLDoc()
{
  var xmlhttp;
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
  }
xmlhttp.open("POST","jsArrayPhp.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("test[]=Henry&test[]=Ford");
}

请注意: test[]=Henry&test[]=Ford"

其中 test 是您将在 php 中使用的数组的名称。

在php中

<?php
 print_r($_POST['test']);
?>

它会产生:Array ( [0] => Henry [1] => Ford )

【讨论】:

    【解决方案4】:

    类似这样的: post 是 POST 或 GET。 参数仅在 POST 中使用,否则在 GET 的 url 中包含您需要的内容。 success 和 error 都是函数的字符串名称,而不是函数本身,这就是为什么需要 executeFunctionByName,感谢 Jason Bunting: How to execute a JavaScript function when I have its name as a string

    getRemoteData = function (url, post,params, success, error){
    
    var http = false;
    if (navigator.appName === "Microsoft Internet Explorer") {
    http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
    http = new XMLHttpRequest();
    }
    
    http.open(post, url, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.onreadystatechange = function() {var resp; if (http.readyState === 4 && http.status == 200) {  resp=http.responseText; executeFunctionByName(success, window, resp); }else if(http.status == 400){resp=http.responseText; executeFunctionByName(error, window, resp);}};
    
    http.send(params);
    return false;
    };
    
    
    function executeFunctionByName(functionName, context, args) {
      args = Array.prototype.slice.call(arguments).splice(2);
      var namespaces = functionName.split(".");
      var func = namespaces.pop();
      for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
      }
      return context[func].apply(this, args);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 1970-01-01
      • 2011-07-16
      • 2016-12-04
      • 2013-12-23
      • 2018-02-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多