简体   繁体   中英

What is the easiest way to send a Javascript array via JSON to PHP?

I have a few arrays that I want to send to process with PHP. Using json2.js I will stringify the arrays like so:

var JSONlinks = JSON.stringify(link_array);
var JSONnotes = JSON.stringify(note_array);

but then I'm confused. Do I need to use a XMLHttpRequest object? Is there another way? If that is the simplest way, could someone please just share the most basic instance of the code needed in order to send to PHP where I can then use JSON decode? I think it might help others in the future really.

I'm currently using Jquery and I know there are many options out there for frameworks and each one may or may not make this process any easier. If you're using a framework in your reply please mention why you'd choose that framework rather than just javascript.

You can send the object many ways in jQuery, most flexibly using $.ajax :

$.ajax({
  type: 'POST',
  url: my_url,
  dataType: 'json',
  data: JSONlinks,
  success: function() { alert('success!') }
});

Bear in mind:

Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key ie {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

See http://api.jquery.com/jQuery.ajax/

Like this:

$.post('path/file.php', 
    { links: link_array, notes: note_array }, 
    function(response) { ... }
);

尝试jquery.post()-> http://api.jquery.com/jQuery.post/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM