How can I send an array to php through ajax?

自闭症网瘾萝莉.ら 提交于 2019-12-17 18:35:23

问题


I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?


回答1:


You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.

You might want to take a look at Creating JSON Data in PHP




回答2:


You might do that with $.post method of jQuery (for example) :

var myJavascriptArray = new Array('jj', 'kk', 'oo');

$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
   // do something with received data!
});

Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.

Is it that ?




回答3:


IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.




回答4:


You may be looking for a way to Serialize (jQuery version) the data.




回答5:


jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:

here is the synatax:

jQuery.ajaxSetting.traditional = true;

here is the example

$.ajax({    
 traditional: true,
 type: "post",
 url: myURL,
 dataType: "text", 
 data: dataToSend, //this will be an array eg. 
 success: function(request) {
  $('#results').html(request);
 }  // End success
 }); // End ajax method



回答6:


You can create an array and send it, as Meador recommended: (following code is Mootooled, but similar in other libraries / plain old JS)

myArray.each(function(item, index)  myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());

That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']

echo $_POST['arrayItems'] ; 

will echo something like: array=>{[0]=>'first thing', [1]=> second thing}



来源:https://stackoverflow.com/questions/299610/how-can-i-send-an-array-to-php-through-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!