这就是我想要实现的目标:
我在网页上有一个元素,我们的电话是 storm 每次用户点击风暴链接时,我都需要以下内容:
我解析返回的JSON没有问题,但我想知道如何执行前两个步骤。 注意:我使用JS比jQuery更多,但我不是纳粹的。
非常感谢你的帮助。
编辑:谢谢@ema再次感谢
function XHR(url, method, data, onsuccess, onfailure, onprogress, onload, onabort) {
var request = new XMLHttpRequest();
// Ten seconds is ought to be enough for anybody.
var xhrtimeout = setTimeout(onfailure, 10000);
request.addEventListener("progress", onprogress, false);
request.addEventListener("load", onprogress, false);
request.addEventListener("error", onfailure, false);
request.addEventListener("abort", onabort, false);
request.addEventListener("readystatechange", function (e) {
if (request.readyState == 4) {
if (request.status == 200) {
clearTimeout(xhrtimeout);
onsuccess(request.responseText);
} else {
onfailure(e);
}
}
});
request.open(method, url, true);
request.send(data);
}
function getJSONAndParse(url, allDone) {
XHR(url, "GET", null, function(data) {
allDone(JSON.parse(data));
}, function() {
alert("error");
});
}
getJSONAndParse("http://lalala.com/json", function(parsedJSON) {
alert(parseJSON[0].name);
console.log(parseJSON);
});
答案 0 :(得分:2)
您可以使用XMLHttpRequest,如下所示:
var r = new XMLHttpRequest();
r.open("POST", "api/url", true);
r.onreadystatechange = function () {
var json = r.responseText;
// parse your json here
};
r.send("storm=value_of_storm&another_param=value_of_whatever");
HTH
答案 1 :(得分:0)
让我看看我是否明白......
从JQuery调用API非常简单,你可以使用$ .ajax(最完整)或$ .post(最简单)
你要调用可以在$(document).ready中绑定的click事件
$(document.ready(function(){
$('.mybuttons').off('click');//to only hit once if you have Postbacks
$('.mybuttons').on('click', myapicall);
});
示例使用$ .ajax:
function myapicall(){
$.ajax({
beforeSend: function () {
// a 'Loading'
},
type: 'POST',
url: 'URL-OF-API',
contentType: 'application/json; charset=utf-8',
data: { stormvalue: 'the sorm value you want to send to API'},
dataType: 'json',
success: function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can """save""" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
},
error: function (xhr, ajaxOptions, thrownError) {
var r = jQuery.parseJSON(xhr.responseText);
alert(r); // show the error of callback
},
complete: function (json) {
alert('sucess!');
}
});
}
使用$ .post
的示例function myapicall(){
$.post('URL-OF-API', { stormvalue: 'the sorm value you want to send to API'},
function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can "save" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
}
);
}
希望我可以帮助你,对不好的英语抱歉; - )