gpt4 book ai didi

jquery - 存储来自 AJAX 的变量

转载 作者:行者123 更新时间:2023-12-01 06:44:57 28 4
gpt4 key购买 nike

如何访问来自函数返回的 ajax 请求的变量?我可以 console.out 变量,但我似乎无法将其存储在范围之外。

它看起来如何:

  1. 在 html 中:

    函数 my_ajax() {

    var stuff = 'stuff';
    return $.ajax({
    type: "POST",
    url: "file.php",
    data: {"something": "wrong"}
    }); /* end ajax */

    }/* 结束 my_ajax() */

...然后在 js 文件中:

my_ajax().then(function(response){
var elements = jQuery.parseJSON(response);
var one = elements.one;
var two = elements.two;

//now say that I need to use 'one' outside this function. I try this:

stuff(elements);

});

//这有效

function stuff(el) {
var something = el.one;
console.log(something);
}

//这不起作用

function stuff(el) {
var something = el.one;
return something;
}

//这有效

var try_obj = {
please_work: function(el) {
var something = el.one;
console.log(something);
}
};

那么我如何存储来自这种性质的 ajax 的变量,以便我可以在 html 页面或 js 文件中重用它们?我需要用另一个 ajax 请求将它们发回。

最佳答案

您使用 Ajax 的方式不正确。我们的想法是不让它返回任何内容,而是将数据交给回调函数来处理数据(例如,您的第二个 AJAX 调用)。

function handleData( responseData ) {

// Do what you want with the data
console.log(responseData);
}

$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});

Reference

关于jquery - 存储来自 AJAX 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34345171/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com