我使用ajax解析URL中的JSON数据。我需要将解析的数组捕获到一个变量中。我该怎么做?谢谢
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
发布于 2017-06-29 20:35:59
您可以使用JSON.parse(data)
将所需的输出转换为JSON,然后分别使用.object
和[array_index]
从其中访问对象和数组索引:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您也不需要传递任何data
,因为您正在执行GET
请求。
希望这会有帮助!)
发布于 2017-06-29 20:51:00
所以我想你不确定ajax调用,所以让我们打破它..
例如:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
发布于 2017-06-29 20:35:23
你可以尝试这样的方法:-
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});
https://stackoverflow.com/questions/44834420
复制相似问题