简体   繁体   English

修改函数内的全局javascript变量

[英]Modify global javascript variable inside a function

I'm trying clone a json object inside a function wanting to access the object outside the function. 我正在尝试在函数内部克隆json对象,以访问函数外部的对象。 But when function is done, the object still seems to be undefined. 但是当函数完成后,该对象似乎仍未定义。 Seems like it's not the same variable? 好像不是相同的变量?

var jsonUserObj;
$.getJSON("user.json", function(content){
    jsonUserObj = $.parseJSON(JSON.stringify(content));
    console.log(content);
    console.log(jsonUserObj); //looks fine!
});
console.log(jsonUserObj); //undefined

inside the callback function it contains all the data, but it does not remain outside of it. 在回调函数内部,它包含所有数据,但不保留在其外部。 How to make it assessible globally? 如何使其在全球范围内可评估?

$.getJSON is asynchronous so console.log at the end of your code runs before $.getJSON returns its result. $ .getJSON是异步的,因此在代码末尾的console.log在$ .getJSON返回其结果之前运行。

You should modify the variable inside the callback (where it looks fine ) and then use the variable inside that function, this callback is the only place where you can guarantee your variable is set. 您应该修改回调中的变量( 看起来不错 ),然后在该函数中使用变量,此回调是唯一可以确保设置变量的地方。

You could also use the synchronous version of $.ajax but that's really not recommended (and probably unnecessary). 您也可以使用$ .ajax的同步版本,但实际上不建议这样做(并且可能没有必要)。

You got a typo: 您输入错误:

console.log(jsonUserObject);

It should be 它应该是

console.log(jsonUserObj);

You need to declare var jsonUserObj outside a function. 您需要在函数外部声明var jsonUserObj

Also it looks like you have a typeo, is it jsonUserObj or jsonUserObject? 看起来你也有打字机,是jsonUserObj还是jsonUserObject?

Could it be a question of timing? 可能是时间问题吗? If that getJSON method is firing asynchronously then it may not have returned it's value by the time you have fired the last line. 如果该getJSON方法异步触发,那么在您最后一行触发时,它可能尚未返回其值。 Does that make sense? 那有意义吗?

$.getJSON performs an ajax call, which is asynchronous. $.getJSON执行ajax调用,该调用是异步的。 The code after it will continue evaluating while it waits for a response. 等待响应时,它之后的代码将继续评估。 When the response comes back, the program flow will jump back into the success/error/complete handlers of the ajax call. 当响应返回时,程序流将跳回到ajax调用的成功/错误/完成处理程序中。

tldr: Anything you do with data from an ajax call must be in the success handler of that ajax call. tldr:您对ajax调用中的数据所做的任何操作都必须在该ajax调用的成功处理程序中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM