简体   繁体   English

无法通过XMLHttpRequest发送大型JSON数据-javascript

[英]Can't send large json data via XMLHttpRequest - javascript

I need to pass a json variable as a paramater to a php script that will process the json data and store it in Database. 我需要将json变量作为参数传递给php脚本,该脚本将处理json数据并将其存储在数据库中。

So first, in javascript, i was testing sending data like this : 所以首先,在javascript中,我正在测试发送数据,如下所示:

$('#sendResult').load('http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal);

This was working well when passing small records (records can vary, it depends the data that user insert). 在传递小记录时,这种方法效果很好(记录可能会有所不同,这取决于用户插入的数据)。

But when i increased the records, it started appearing this error in console: 但是当我增加记录时,它开始在控制台中出现此错误:

414 (Request-URI Too Long)

I've changed the js code to: 我已将js代码更改为:

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal );
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.send();

But still appearing the same error with POST method. 但是与POST方法仍然出现相同的错误。 I've checked the json param and it has 5439 characters. 我检查了json参数,它有5439个字符。

How can i resolve this? 我该如何解决? Thanks in advance. 提前致谢。

Please note that the length can be 8x more than 5439 characters. 请注意,长度可以是5439个字符的8倍。

Don't use a GET request. 不要使用GET请求。

You're storing data, so you should be using a POST request anyway. 您正在存储数据,因此无论如何应该使用POST请求。

Use $.post instead of $.load and write your own logic to display the response in the done() handler. 使用$.post而不是$.load并编写自己的逻辑以在done()处理程序中显示响应。


I've changed the js code to: 我已将js代码更改为:

You need to put the data in the body of the request. 您需要将数据放入请求的正文中。 POST requests don't change the rules for how much data you can put in the URL. POST请求不会更改可在URL中放入多少数据的规则。


$.post("http://localhost/myurl/phpFile.php", { mrData: jsonArrFinal })
 .done( data => $("#sendResult").html(data) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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