简体   繁体   English

服务器未看到JavaScript Ajax请求中发送的JSON

[英]Server not seeing the JSON sent in javascript ajax request

I'm trying to make an ajax request in straight javascript (jQuery is not available to me) with some JSON parameters. 我正在尝试使用一些JSON参数在纯JavaScript(jQuery对我不可用)中提出ajax请求。 The javascript: JavaScript:

var params = {'ajax': true, 'albumid': albumid, 'sequencenum': sequencenum};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
    if (xhr.readyState==4 && xhr.status==200)
    {
        console.log(xhr.responseText);
    }
}
xhr.open("GET","viewpicture.php",true);
xhr.setRequestHeader("Content-Type", "application/json")
console.log("sending request");
xhr.send(JSON.stringify(params));

In viewpicture.php, a var_dump($_GET) yields an empty array. 在viewpicture.php中,var_dump($ _ GET)产生一个空数组。 What am I doing wrong? 我究竟做错了什么?

In short, when you make a GET request, .send is expected to have 0 params (or be null ). 简而言之,当您发出GET请求时, .send预期具有0个参数(或为null )。 The only way to send the data through GET would be to append it to the URL itself. 通过GET发送数据的唯一方法是将其附加到URL本身。

To wit: 以机智:
If you were sending in form-data, in a POST , the anticipation would be that send would contain the form-encoded data (json for json-data, etc), and the URL would just be the access point on the server. 如果您要在POST中发送表单数据,则可以预期send将包含表单编码的数据(json为json-data等),而URL只是服务器上的访问点。

A GET request is just fetching data from that access point (including query string). GET请求只是从该访问点获取数据(包括查询字符串)。
See where I'm going with this? 看看我要去哪里?

So if you want this to work in a GET , you need to set your JSON as a property of a query parameter (or turn it into query params/values). 因此,如果您希望它在GET工作,则需要将JSON设置为查询参数的属性(或将其转换为查询参数/值)。

If you want to send in the request body you should use a POST request, however if you need to use a get request you should send the data as key value pairs in the url. 如果要发送请求正文,则应使用POST请求,但是,如果需要使用get请求,则应将数据作为键值对发送到url中。 eg xhr.open("GET","viewpicture.php?data=" + encodeURIComponent(JSON.stringify(params)),true); 例如xhr.open("GET","viewpicture.php?data=" + encodeURIComponent(JSON.stringify(params)),true); Then retrieve via $_GET['data'] . 然后通过$_GET['data']检索。

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

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