Javascript 使用 JSON POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11456771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using JSON POST Request
提问by GK1667
I'm attempting to use JSON to initiate a POST request to an API.
我正在尝试使用 JSON 向 API 发起 POST 请求。
I've found some example code, and before I get too far I wanted to get that working, but I'm stuck...
我找到了一些示例代码,在我走得太远之前,我想让它工作,但我被卡住了......
<html>
<head>
<script type="text/javascript">
function JSONTest()
{
requestNumber = JSONRequest.post(
"https://example.com/api/",
{
apikey: "23462",
method: "example",
ip: "208.74.35.5"
},
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
} else {
processError(exception);
}
}
);
}
</script>
</head>
<body>
<h1>My JSON Web Page</h1>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
This is a .html file, which I am running in chrome. Nothing happens when I click the button...
这是一个 .html 文件,我在 chrome 中运行。当我点击按钮时没有任何反应......
I think I'm missing a piece of javascript which interprets the JSON response and can be displayed? otherwise any other advice?
我想我错过了一段解释 JSON 响应并可以显示的 javascript?否则有什么其他建议吗?
回答by Phil
An example using jQuery is below. Hope this helps
下面是一个使用 jQuery 的例子。希望这可以帮助
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "https://example.com/api/",
type: "POST",
data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
Firebug debug process
Firebug 调试过程
回答by Ivan
Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html(please note that it has a few dependencies).
现代浏览器目前没有实现 JSONRequest(据我所知),因为它现在只是一个草案。我发现有人将它实现为可以包含在页面中的库:http: //devpro.it/JSON/files/JSONRequest-js.html(请注意它有一些依赖项)。
Otherwise, you might want to go with another JS library like jQuery or Mootools.
否则,您可能想要使用另一个 JS 库,如 jQuery 或 Mootools。