[英]Using JSON POST Request
我正在嘗試使用JSON來啟動對API的POST請求。
我找到了一些示例代碼,在我走得太遠之前我想讓它工作,但我被卡住了......
<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>
這是一個.html文件,我在chrome中運行。 單擊按鈕時沒有任何反應......
我想我錯過了一段解釋JSON響應並可以顯示的javascript? 否則任何其他建議?
下面是一個使用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調試過程
現代瀏覽器目前沒有實現JSONRequest(據我所知),因為它現在只是一個草案。 我發現有人將其實現為您可以包含在您的頁面中的庫: http : //devpro.it/JSON/files/JSONRequest-js.html (請注意它有一些依賴項)。
否則,您可能想要使用另一個JS庫,如jQuery或Mootools。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.