jQuery(跨域).getJSON,将响应存储在可重用变量中
我想从当前用户获取 IP 并将其与 AJAX POST 一起发送到 PHP 文件。这意味着我需要重新使用从 IP .getJSON 请求的响应中获得的变量。
脚本 1: 我在 snipt 上找到了这个方便的片段:
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
alert( "Your ip: " + data.ip);
});
脚本 1 工作并给出一个带有您的 IP 的警报对话框。
脚本2:我将脚本1转换为:
var ipAppspot;
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
ipAppspot = data.ip;
});
alert(ipAppspot);
据我所知,不在变量前面声明'var'关键字使其可用甚至在函数(全局)之外的所有范围。虽然我想如果脚本2可能不是跨域请求,那么它应该可以工作,但在这种情况下,它会给出一个带有'未定义'的警报对话框 所以这个例子不起作用
在Stackoverflow上还有另一个问题jQuery-storing-ajax-response-into-global-variable 处理同样的问题。
并附加他们提供的解决方案,我得到以下结果。
脚本 3:从链接
// https://stackoverflow.com/questions/905298/jquery-storing-ajax-response-into-global-variable
var ipStore = (function(){
var ipAppspot;
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){ipAppspot = data.ip;});
return {getIp : function()
{
if (ipAppspot) return ipAppspot;
// else show some error that it isn't loaded yet;
}};
})();
alert(ipStore.getIp());
“脚本 3”附加解决方案 给出与“脚本 2”相同的问题,即“未定义” em>
问题: 我如何在以后的脚本中重复使用此变量?
编辑 Nick Cravers 的答案
var ipAppspot;
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
ipAppspot = data.ip;
myFunc();
});
function myFunc() {
alert(ipAppspot);
}
由 Nick Craver 编写,实际上确实有效。
function dataAuth(ip){
// collect data from form
var usernameRaw = $('#feg-username').val();
var passwordRaw = $('#feg-password').val();
// phpFile is our back-endgine
var phpFile = 'feg/back-endgine.php';
// construct the JSON in a variable
var dataConstruct = "username=" + usernameRaw + "&password=" + passwordRaw + "&ip=" + ip;
// start the AJAX
$.ajax({
type: "POST",
url: phpFile,
dataType: "json",
data: dataConstruct,
success: function(msg){
alert(msg);
}
});
} // END dataAuth
这是在我的应用程序中,我会这样使用该函数:
$('body').delegate('#feg-submit', 'click', function(){
$(this).attr('disabled','disabled');
console.log('submit button clicked');
dataAuth(ipAppspot);
return false
});
所以我会在那里使用 ipAppspot,稍后我需要 AJAX 请求的 IP,有什么方法可以实现它吗?
I want to get the IP from the current user and send it along with an AJAX POST to a PHP file. Which means I need to re-use the variable I get in the response from the IP .getJSON request.
Script 1: I found this handy snippet on snipt:
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
alert( "Your ip: " + data.ip);
});
Script 1 works and gives an alert dialog with your IP.
Script 2: I converted script 1 into this:
var ipAppspot;
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
ipAppspot = data.ip;
});
alert(ipAppspot);
As I understand that not declaring the 'var' keyword in front of a variable makes it avaible to all scopes even outside the function (global). Though I guess that should work if script 2 wouldn't be a Cross-domain request maybe, but in this case it gives an alert dialog with 'undifined' So this example won't work though
On Stackoverflow there is another question jQuery-storing-ajax-response-into-global-variable which deals with about the same problem.
And appending the solution they give I get the following.
Script 3: Appending the solution from the link
// https://stackoverflow.com/questions/905298/jquery-storing-ajax-response-into-global-variable
var ipStore = (function(){
var ipAppspot;
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){ipAppspot = data.ip;});
return {getIp : function()
{
if (ipAppspot) return ipAppspot;
// else show some error that it isn't loaded yet;
}};
})();
alert(ipStore.getIp());
Script 3 Gives the same problem as script 2, which is 'undefined'
Question: How can I re-use this variable in later uses in my script?
EDIT for Nick Cravers answer
var ipAppspot;
$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
ipAppspot = data.ip;
myFunc();
});
function myFunc() {
alert(ipAppspot);
}
by Nick Craver, which does in fact works.
function dataAuth(ip){
// collect data from form
var usernameRaw = $('#feg-username').val();
var passwordRaw = $('#feg-password').val();
// phpFile is our back-endgine
var phpFile = 'feg/back-endgine.php';
// construct the JSON in a variable
var dataConstruct = "username=" + usernameRaw + "&password=" + passwordRaw + "&ip=" + ip;
// start the AJAX
$.ajax({
type: "POST",
url: phpFile,
dataType: "json",
data: dataConstruct,
success: function(msg){
alert(msg);
}
});
} // END dataAuth
This is in my application, and I would use the function as such:
$('body').delegate('#feg-submit', 'click', function(){
$(this).attr('disabled','disabled');
console.log('submit button clicked');
dataAuth(ipAppspot);
return false
});
So I would use the ipAppspot there, and I would need the IP for AJAX requests later on, is there any way I could implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是范围问题,而是时间问题,让我们用一个确实有效的示例来说明它,如下所示:
您可以在这里测试。请注意,它确实会提醒您的 IP,那么这里有什么不同呢?在填充变量之前,您不会询问变量(通过调用
alert()
),这发生在$.getJSON()
回调。因此范围不是问题,但事实上回调运行稍后(当响应返回时)是一个问题,只需启动需要来自回调,因为这是数据第一次可用。这是一个更常见的示例,将数据直接传递到它所在的地方:
或者,简短的版本:
It's not a scoping issue, it's a timing issue, let's illustrate it with an example that does work, like this:
You can test it here. Notice it does alert your IP, so what's different here? You're not asking for the variable (by calling
alert()
) until the variable is populated, and this happens in the$.getJSON()
callback. So the scope isn't an issue, but the fact that the callback runs later (when the response comes back) is an issue, just initiate whatever needs the data from the callback, since that's the first time the data's available.Here's a more common example, passing the data directly to wherever it goes:
Or, the short version:
您的警报发生在异步操作完成之前,因此当时未定义。如果您将警报放置在回调中,您会发现它(可能)已正确定义。如果您想分配并重用该变量,请在回调触发之前不要尝试这样做。也许需要该值的逻辑可以放置在从回调调用的函数中?
Your alert occurs before the asyc operation has completed and therefore is undefined at that time. If you place the alert within the callback, you will find that it is (probably) correctly defined. If you want to assign and reuse the variable, don't attempt to do so until the callback has fired. Perhaps the logic that requires this value could be placed in a function that is called from the callback?
Ajax 是异步的。重构以便您在回调中执行条件。
或者使 async 为 false。
Ajax is asynchronous. Refactor so you do the conditionals in the callback.
That or make async false.