简体   繁体   中英

What is a good way to send large JSON file from javascript to php?

I would like to send a large JSON file ( > 110k characters) from javascript to php. I am willing to use any method that will work. I can get around 60k characters using xmlhttp transfer commands but anymore than that and the string is chopped off. Here is a small example of how I am currently performing the transfer:

xmlhttp.open("POST","my.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
xmlhttp.send("obj=" + (JSON.stringify(myObj)) + "&" + "name=" +document.getElementById("textBox1").value);

I have also tried but it makes the string longer which I wouldnt care about as long as it transferred all of the string:

xmlhttp.open("POST","my.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
xmlhttp.send("obj=" + encodeURIComponent((JSON.stringify(myObj))) + "&" + "name=" +document.getElementById("textBox1").value);

There is no limit on HTTP post requests that I know of, if your string is being chopped of it could be to improper formatting or a transfer limit specified on your server.

You could try using Jquery.Ajax it's a wrapper for xhttp protocol:

var name = $('#textBox1').val();
var content = encodeURIComponent((JSON.stringify(myObj)));
console.log(content)
//make sure this is what you expect it is.
$.ajax({
      url: 'http://yourserver.com/my.php',
      async: false,
      type: 'POST',
      data: ({'content':content,'name':name}),
      dataType: 'html',
      success: function(data) {


      },
      error:function(jqXHR, textStatus, errorThrown){
      alert("Error type" + textStatus + "occured, with value " + errorThrown);
      }
      });

Server:

$data= POST['content'];

Since there was never an answer, the way I fixed this problem was to write a function that chopped the string up into pieces. Then I wrote an ajax function to send the pieces one at a time to the php. On the php side I handled the separate pieces. I would suggest that when you send the string pieces, you also send a number telling the php which piece it is looking at. This is probably not the best way to handle this issue but it works every time so that is good enough for me!

Good luck, if you have any questions then let me know!

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