当前位置: 动力学知识库 > 问答 > 编程问答 >

ajax - Submit form to REST API

问题描述:

Hi i have the following code

var dataString = "[email protected]&fname=John&lname=Doe&phone=7851233&vid=726&size=2&date=2013-05-28%202:15%20PM&request=Testing%20A%20Message";

$.ajax({

type: "GET",

timeout: 5000,

url: "http://www.livepicly.com/app/api.php?method=add_reservation",

data: dataString,

success: function(data, textStatus) {

alert(data.result);

},

error: function(xhr, textStatus, errorThrown){

alert("ERROR");

}

});

return false;

Where basically i would like to submit a piece of string to this URL:

http://www.livepicly.com/app/api.php?method=add_reservation

The formatted string (as displayed by firebug) is like this:

http://www.livepicly.com/app/api.php?method=add_reservation&[email protected]&fname=John&lname=Doe&phone=7851233&vid=726&size=2&date=2013-05-28%202:15%20PM&request=Testing%20A%20Message

When the string is executed via browser (straight copy-pasting) it works perfectly. It displayed the corresponding message.

However, when i execute the code, it always returns error. Does anyone know why this happen?

Cheers,

网友答案:

The API in question is not RESTful.

Anyway, your problem is a combination of factors. What it definitely is NOT is the API actually throwing an error, as all errors are returned as 200 status codes. (Not RESTful Point #1). So, even if livepicly returned an error, it'd still count as success on jQuery handlers.

In no particular order:

  • The API is not throwing Access-Control-Allow-Origin headers. It does not support JSONP either. (This can be seen by querying http://www.livepicly.com/app/api.php?method=add_reservation&callback=test ). This will completely prevent jQuery from loading any data of performing any queries to the API due to cross-domain restrictions

That's the only thing that is failing! This is also completely preventing jQuery usage. You'll need to make a choice to go around this one, which may or may not include:

  • Proxying the API locally. This is trivial if your webserver is running thanks to Apache or nginx. For Apache, use ProxyPass and ReverseProxyPass directives using mod_proxy, or use a rewrite rule with the [P,L,QSA] set of flags. On nginx, use the proxy_pass directives. If you have access to neither, proxy it using curl through PHP.
  • Giving the developers of the API a slap in order for them to simply add Access-Control-Allow-Origin: * to the headers, which will make your call work
  • Giving the developers of the API a slap in order for them to support JSONP

Overall, just point them to https://en.wikipedia.org/wiki/Representational_state_transfer and give them a slap for me. Please?

分享给朋友:
您可能感兴趣的文章:
随机阅读: