Home > Article > Backend Development > How to Efficiently Send Large Arrays to PHP Scripts Using Ajax?
Send Large Array to PHP Script Using Ajax
When dealing with transmitting large arrays to PHP scripts via Ajax, it's important to consider the most efficient approach. Using the .push function to create an array can result in substantial data.
Solution:
The recommended method is to encode the data array into JSON using JSON.stringify(). JSON is a standard for representing structured data as a string.
The modified Ajax code now encodes the data array into JSON and sends it with a data key:
var jsonString = JSON.stringify(dataString); $.ajax({ type: "POST", url: "script.php", data: {data: jsonString}, cache: false, success: function(){ alert("OK"); } });
PHP Script Modification:
$data = json_decode(stripslashes($_POST['data'])); foreach($data as $d){ echo $d; }
Note:
It's crucial to use a key-value pair when sending data via POST. Instead of data: dataString, use data: {data: dataString} to ensure the correct format for POST data.
The above is the detailed content of How to Efficiently Send Large Arrays to PHP Scripts Using Ajax?. For more information, please follow other related articles on the PHP Chinese website!