2016-01-06 41 views
0

在Google Chrome的开发控制台中提交表单后,会有一个XHR application/json类型的请求,将数据发布到另一个服务器。使用JavaScript将请求负载存储到localStorage

POST请求包含一个JSON数组,我试图抓住其中一个参数并将其存储在localStorage或sessionStorage中供以后使用。

是否可以在前端仅使用JavaScript?我正在考虑......当请求url为http://example.com/service时,然后抓住JSON对象并选择'name'元素并将其设置为localStorage中的'name'键。

回答

0

您可以使用 “全局AJAX事件处理程序”,从jQuery的:

$(document).ajaxComplete(function(event, xhr, settings) { 
    if (settings.url === 'http://example.com/service') { 
    // do your processing - grab JSON (from XHR) and store it to localstorage 
    } 
}); 

也可以手动也补丁的XMLHttpRequest:

(function() { 

    var proxied = window.XMLHttpRequest.prototype.open; 

    window.XMLHttpRequest.prototype.open = function() { 
     console.log(arguments); 

     if (arguments[1].indexOf('/service') > -1) { 
      // do your processing 
     } 

     return proxied.apply(this, [].slice.call(arguments)); 
    }; 

})(); 
+0

我想ajaxComplete的,但我坚持只使用纯粹的JavaScript。这就是我不知道如何从XHR请求中获取JSON的地方。 – TheIntrepidSpiff

+0

您也可以直接使用XMLHttpRequest(全局),更新答案 –