如何从同一文件中的外部函数访问响应变量 [英] How to access the response variable from outside functions in the same file

查看:72
本文介绍了如何从同一文件中的外部函数访问响应变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<pre>
var json="";
var xrequest = new XMLHttpRequest();
xrequest.open('GET', 'videos.json', true);
xrequest.onload = function(){
	if(this.status == 200) {
		var json = JSON.parse(this.responseText);
		for(var i=0; i<json.length; i++) {
			console.log(json[i].url);
		}
		console.log(json + ' 1');
	}
}
xrequest.send(null);

console.log(json);





我尝试了什么:



此代码从json文件中读取,响应分配给var json,然后我想访问json来自函数外部,



global var json =;

我假设这个var json被赋值给json.parse对象,

控制台日志打印var json成功分配给响应对象json.parse,



但是现在我试图在xmlhttprequest对象之外操作它,但它没有返回任何内容,为什么json响应在xmlhttprequest之外没有被拒绝,



如何在函数外部访问对象响应? pls sos,help



What I have tried:

this code reads from json file and the response is assigned to var json, then i wanna access the json from outside the function,

global var json="";
im supposing this var json gets assigned to json.parse object,
console logs prints that var json successfully assigned to response object json.parse,

however now im trying to manipulate it outside the xmlhttprequest object, but it returns nothing, why the json response has disappreared outside the xmlhttprequest,

how can i access the object response outside the function??? pls sos, help

推荐答案

你无法访问它的原因是因为在函数内部它也说

The reason you cannot access it is because inside the function it also says
var json =



这意味着它声明了一个名为json的新变量。只需删除var,它将分配给全局json变量。


which means it declares a new variable named json. Just remove the var and it will assign to the global json variable.


Quote:

xrequest.send(null);
console.log(json);



XMLHttpRequest.send() [ ^ ]方法立即返回 。它不会等到收到回复。



json 变量在响应之前没有分配已收到。因此,在您对 console.log json 变量仍为 undefined c $ c>。



您需要重新思考自己在做什么。


The XMLHttpRequest.send()[^] method returns immediately. It does not wait until the response has been received.

The json variable is not assigned until the response has been received. Therefore, the json variable is still undefined in your call to console.log.

You need to re-think what you're doing.


这篇关于如何从同一文件中的外部函数访问响应变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆