使用普通的js在AJAX请求上传递数组?

时间:2013-10-17 14:20:03

标签: javascript jquery ajax

我正在使用jQuery在POST请求上传递数组,但我不明白如何使用“vanilla”javascript执行相同操作。这是我的jQuery:

    // Request using jQuery
$.ajax({type:'POST',url:'insert-user.php',data: {myArray: myArray},
success:function(data_response){
    console.log("jQuery, got data back, response: "+data_response);
}});

目前我正在尝试使用普通的js:

// Request using plain js
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){
        console.log("JS, got data back, response: "+xmlhttp.responseText);
    }
}
xmlhttp.open("POST","insert-user.php",true);
xmlhttp.send({myArray: myArray});

2 个答案:

答案 0 :(得分:2)

.send()方法接受一个字符串,该字符串是要在请求中发送的POST数据。在jQuery中,data属性允许您传递一个对象(您拥有),但在幕后,jQuery将对象转换为键/值对格式。

这是您必须传递给.send()的格式,因为它不会自动将对象转换为键/值字符串。

例如,要发送包含三个元素的myArray

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send('myArray[]=first&myArray[]=second&myArray[]=third');

请记住包含标题,告诉服务器端您要发送POST数据的格式。

将简单的1维数组转换为此格式的函数可能如下所示:

function arrayToKeyValueString(name, arr){
    var str = name + '[]=';
    for(var i=0; i<arr.length; i++){
        arr[i] = encodeURIComponent(arr[i]);
    }

    str += arr.join('&' + name + '[]=');
    return str;
}

var myArray = ['one', 'two', 'three'];

console.log( arrayToKeyValueString('myArray', myArray) );
// outputs: myArray[]=one&myArray[]=two&myArray[]=three 

使用普通的Javascript ajax时,通常更容易JSON编码数据并发送字符串而不是尝试构建键/值字符串。

xmlhttp.send('myArray=' + encodeURIComponent(JSON.stringify(myArray)));

答案 1 :(得分:2)

使用此:

xmlhttp.send('myArray='+JSON.stringify(myArray));

在php端,

$array= json_decode($_POST['myArray']);
相关问题