【问题标题】:Making an API call in Javascript - new call at each click在 Javascript 中进行 API 调用 - 每次点击都有新的调用
【发布时间】:2014-02-13 15:22:00
【问题描述】:

这是我想要实现的目标:

我在网页上有一个元素,我们称之为 storm
每次用户点击 storm 链接时,我想要以下内容:

  • 执行一个 API 调用,其中参数是预定义的,但 storm 字符串作为其中之一
  • 将结果(API 生成 JSON 文件)存储在某处
  • 用一种或另一种方法解析结果。

解析返回的 JSON 没有问题,但我想知道如何执行前两个步骤。 注意:我使用 JS 多于 jQuery,但我不是纳粹。

非常感谢您的帮助。

编辑:谢谢@ema
我有一个 XHR 模型,附在此处。 你能帮我确定我必须在哪里添加我的 API url(根据我的理解,第一个问号之前是什么),以及如何向其中添加预定义参数和自定义参数(一个字符串,包含风暴例如)?

再次感谢

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);
});

【问题讨论】:

  • $.postXMLHttpRequest 应该可以解决问题。确切的调用和说明取决于您正在处理的 API。

标签: javascript jquery json api


【解决方案1】:

你可以使用 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

【讨论】:

  • 谢谢@ema。刚刚更精确地编辑了问题。
【解决方案2】:

让我看看我是否理解..

从 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
        }
    }
);
}

希望我能帮助你,抱歉英语不好,;-)

【讨论】:

    猜你喜欢
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多