And*_*zos 5 javascript ajax jquery http
我有一个服务器端功能:
string foo(string input_string);
Run Code Online (Sandbox Code Playgroud)
例如:
foo("bar") returns "baz"
Run Code Online (Sandbox Code Playgroud)
并将此功能包装到HTTP服务器中,以便:
POST /foo HTTP/1.1
...
bar
Run Code Online (Sandbox Code Playgroud)
将返回:
HTTP/1.1 200 OK
...
baz
Run Code Online (Sandbox Code Playgroud)
即,带有输入字符串的POST请求作为HTTP消息正文将返回输出字符串作为200 OK的HTTP消息正文.
现在我在网页上的javascript中有两个功能:
function sendFoo(input_string)
{
??? // should asynchronously start process to POST input_string to server
}
function recvFoo(output_string)
{
...
}
Run Code Online (Sandbox Code Playgroud)
当我调用sendFoo时,我希望POST与服务器异步进行,稍后当收到响应时,我希望recvFoo调用(可能在另一个线程或其他任何内容中),消息正文为200 OK.
我如何实现上面的sendFoo?我目前正在使用jQuery,但纯javascript的解决方案也可以.(如果需要,我也可以修改服务器?)
方案:
function sendFoo(input_string)
{
$.ajax({ url: "/foo", type: "POST", data: input_string, success: recvFoo });
}
Run Code Online (Sandbox Code Playgroud)
XMLHttpRequestobject的open()方法允许您指定HTTP方法,而send()方法允许指定消息体,例如
var xhr = ... // obtain XMLHttpRequest object
xhr.open('POST', '/foo'); // HTTP method and requested URL.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
recvFoo(xhr.responseText); // Will pass 'baz' to recvFoo().
}
};
xhr.send('bar'); // Message body with your function's argument.
Run Code Online (Sandbox Code Playgroud)
无需回归经典 JavaScript
$.ajax({
url:"URL of foo...",
type: "POST",
data: "what ever",
success: recvFoo
});
Run Code Online (Sandbox Code Playgroud)
或post选项:
$.post('The url of foo', {input_string : 'bar'}, recvFoo);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2101 次 |
| 最近记录: |