简体   繁体   English

Jquery中对REST服务的AJAX请求,当参数通过URL发送而不是通过数据对象发送时获得响应

[英]AJAX request for REST service in Jquery, Getting response when parameters are sent through URL but not through data object

I'm using a ajax request for calling a REST service and I'm using post method to pass parameters. 我正在使用ajax请求来调用REST服务,并且正在使用post方法来传递参数。 I get the response from the REST service when I pass the parameters in the REST URL, but when I send the parameters through data object I dont get any response. 当我在REST URL中传递参数时,我会从REST服务获得响应,但是当我通过数据对象发送参数时,我没有任何响应。 Am I doing anything wrong? 我做错什么了吗?

$.ajax({
  type: "POST",
  url: "myURL?ID=5087&name=hello",
     data:{
        'id':'5087',
        'name':'hello',

    },
  success: function(msg){
      alert('wow' + msg);
  }

});

In the above request If i remove the parameters from the URL and keep the data object as it is, I'm not getting any response 在上述请求中,如果我从URL中删除参数并保持数据对象不变,则不会收到任何响应

You're not doing anything wrong, the issue is that the API is not following semantic rules. 您没有做错任何事情,问题在于API没有遵循语义规则。

When receiving a POST request the data should be sent through the body of the request except for possibly an identifier which can be in the URL. 当接收到POST请求时,数据应通过请求的正文发送,但可能在URL中的标识符除外。 For this reason, when you specify type: 'POST' and provide an object to data , that's where jQuery puts the information you send. 因此,当您指定type: 'POST'并为data提供一个对象时,jQuery将在其中放置您发送的信息。

However, the API you're calling is retrieving the data you send in the POST request via the URL, when that should in fact be done with a GET request. 但是,您正在调用的API会检索通过URL在POST请求中发送的数据,而实际上应该使用GET请求来完成。

Due to this you will have to manually append the data to the URL in application/x-www-form-urlencoded format, as you are doing in the working example. 因此,您必须像在工作示例中一样,将数据手动以application/x-www-form-urlencoded格式附加到URL。

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

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