2014-02-13 3 views
0

Вот что я хочу добиться:Выполнение вызова API в Javascript - новый вызов на каждый клик

У меня есть элемент на веб-странице, давайте вызов шторм
Каждый раз, когда пользователь нажимает на буря ссылку, я хочу следующее:

  • выполнить вызов API, какие параметры определены заранее, но с штормовой строки, как один из них
  • сохранить результат (API генерирует файл JSON) где-то
  • разобрать результат тем или иным способом.

У меня нет проблем с обработкой JSON, но я хотел бы знать, как сделать первые два шага. NB: Я использую JS больше, чем jQuery, но я не нацистский на этом.

Большое спасибо за помощь.

EDIT: thanks @ema
У меня есть модель XHR, прилагаемая сюда. Можете ли вы помочь мне определить, где я должен добавить свой URL-адрес API (из того, что я понял, что перед первым знаком вопроса), и как добавить к нему предварительно определенные параметры и настраиваемый параметр (строка, содержащий шторм например)?

Еще раз спасибо

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

'$ .post' или' XMLHttpRequest' должен делать трюк. Точный вызов и инструкции зависят от API, с которым вы имеете дело. –

ответ

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

НТН

+0

спасибо @ema. Просто отредактировал вопрос с большим количеством исправлений. – basbabybel

0

Позвольте мне увидеть, если я понял ..

Для вызова API из JQuery очень просто, и вы используете $ .ajax (наиболее полный) или $ .post (самый простой)

как вы звоните на события мыши, которые можно связать в $ (документ) .ready с

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

Надеюсь, что смогу вам помочь, и извините за плохой английский, ;-)

Смежные вопросы