我必须从两个不同的 URL 获取值,然后将其合并。我知道如果我在一个 URL 中获取所有数据会更好,但这就是我所拥有的方式,我需要使用它。
我想打印出a_value
的值,但是打印出来了,而b
还没有返回他的值。我已经阅读了一些关于如何使函数同步的文章,但仍然不知道如何将其实现到我的代码中,也不知道什么是适合我的情况的最佳解决方案。我是 JavaScript 的新手,仍然需要一些帮助和指导。
function any_function() {
$.ajax(
{
url : '/url1',
type: "GET",
success:function(data, textStatus, jqXHR)
{
$("#print").html(a(data));
}
});
}
function a(data){
x = 'any value' //`do something with data and insert to this variable`
a_value = x + b(`some id that extracted from data`)
return a_value
}
function b(id){
$.ajax({
url: '/url2',
type: 'GET',
success: function (data, textStatus, jqXHR) {
b_value = c(data, id)
}
});
return b_value
}
function c(data, id){
//do something with `data` and return the value
return c_value
}
最佳答案
function f() {
var request1 = $.ajax({
url : '/url1',
type: 'GET'
});
var request2 = $.ajax({
url: '/url2',
type: 'GET'
});
$.when(request1, request2).done(function(result1, result2){
data1 = result1[0]
data2 = result2[0]
// r1 and r2 are arrays [ data, statusText, jqXHR ]
// Do stuff here with data1 and data2
// If you want to return use a callback or a promise
})
}
关于javascript - 在 ajax 中使用两个 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36239196/