问题描述
我想有一个函数抓起物体从另一个页面上的PHP文件。我使用jQuery的AJAX功能做JSON抢,这是正常工作。问题是,当我试图从函数返回的对象。
我第一次登录的对象(从成功函数内),它是在控制台中正确的,但是从功能getGantt()日志返回的对象为不确定。
我如何得到这个对象该功能的?
我的code:
函数getGantt(requestNumber){
VAR ganttObject;
$阿贾克斯({
键入:POST,
网址:get_gantt.php
数据:{request_number:requestNumber},
成功:函数(的returnValue){
ganttObject = $ .parseJSON(的returnValue);
执行console.log(ganttObject); //这个记录一个正确的对象在控制台
}
});
返回ganttObject;
}
$(函数(){//文件准备功能
VAR requestNumber = $('#request_number)文本()。
VAR ganttObject = getGantt(requestNumber);
执行console.log(ganttObject); //这个记录不确定
}); // end文档准备功能
Ajax中的A是首字母缩写词的重要组成部分。异步JavaScript和XML是异步的。
$阿贾克斯({成功:someFunction})。
手段的做一个HTTP请求,并在响应到达,运行 someFunction
的
返回ganttObject
运行之前响应到达。
您想要做数据您应该做的事情里面 someFunction
,而不是试图将数据返回给调用函数。
I am trying to have a function grab an object from a php file on another page. I'm using the jQuery ajax function to to do the json grab, which is working correctly. The issue is when I try to return that object from the function.
The first time I log the object (from within the success function) it is correct in the console, but the returned object from the function getGantt() logs as "undefined".
How do I get this object out of the function?
My code:
function getGantt(requestNumber){
var ganttObject;
$.ajax({
type: "POST",
url: "get_gantt.php",
data: {request_number: requestNumber},
success: function(returnValue){
ganttObject = $.parseJSON(returnValue);
console.log(ganttObject); //this logs a correct object in the console
}
});
return ganttObject;
}
$(function(){ //document ready function
var requestNumber = $('#request_number').text();
var ganttObject = getGantt(requestNumber);
console.log(ganttObject); //this logs "undefined"
}); //end document ready function
The A in Ajax is an important part of the acronym. Asynchronous JavaScript and XML is asynchronous.
$.ajax({success:someFunction})
means Make an HTTP request and when the response arrives, run someFunction
return ganttObject
runs before the response arrives.
You should do anything you want to do with the data inside someFunction
and not try to return data to the calling function.
这篇关于使用Javascript - 局部范围的对象不能从嵌套函数访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!