[英]Javascript passing object from include file to page
I have created a javascript object and a function to build a new instance of the object. 我创建了一个javascript对象和一个函数来构建该对象的新实例。 I now need to use this object on my page but am not having any luck, I feel that I am missing something.
现在,我需要在页面上使用该对象,但是没有运气,我觉得自己缺少了一些东西。
JS Include File JS包含文件
function MyObject() {
this.ID = 0;
this.Name = "";
}
function GetObject(param1, param2) {
//ajax call to get json string
$.ajax({ //leaving out details this part works
success: function(data) {
var jsonData = $.parseJSON(data.d);
var myObj = new MyObject();
myObj.ID = jsonData[0].ID;
myObj.Name = jsonData[0].Name;
return myObj;
});
}
This call works fine, however when I try to access the data on the page I get undefined
此调用工作正常,但是当我尝试访问页面上的数据时,我
undefined
Page 页
<script type="text/javascript">
$(function() {
var o = GetObject(1, 2);
});
</script>
I was able to get it to work by passing a DOM object through to the function and assigning it there. 通过将DOM对象传递给函数并在其中分配它,我能够使其工作。
function GetObject(param1, param2, domObj) {
//ajax call to get json string
$.ajax({ //leaving out details this part works
success: function(data) {
var jsonData = $.parseJSON(data.d);
var myObj = new MyObject();
myObj.ID = jsonData[0].ID;
myObj.Name = jsonData[0].Name;
domObj.text(myObj);
});
}
However this doesn't work for my application as I'm pull a lot of objects and would like to just reference them on the page. 但是,这对我的应用程序不起作用,因为我要拉很多对象,并且只想在页面上引用它们。 What am I missing?
我想念什么? Any help is greatly appreciated.
任何帮助是极大的赞赏。
Just resign your GetObject
like this: 刚辞职的
GetObject
是这样的:
function GetObject(param1, param2, callback) {
//ajax call to get json string
$.ajax({ //leaving out details this part works
success: function(data) {
var jsonData = $.parseJSON(data.d);
var myObj = new MyObject();
myObj.ID = jsonData[0].ID;
myObj.Name = jsonData[0].Name;
// pass myObj via callback function parameter
return callback( myObj );
});
}
Now call it like: 现在这样称呼:
$(function() {
var o = {};
GetObject(1, 2, function(response) {
o = response;
});
});
As, within GetObject
there is an AJAX request (asynchronous process) and object returned after ajax success
function execute, so you need to take the help of callback
function. 由于在
GetObject
有一个AJAX请求(异步过程),并且在执行ajax success
函数后返回了对象,因此您需要借助callback
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.