函数返回json并想调用另一个函数 [英] function return json and want to call another function

查看:186
本文介绍了函数返回json并想调用另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回JSON对象的函数,我将这个函数调用到另一个函数中。

在第二个函数中没有读取第一个json对象并在javascript中得到未定义的错误。 br $> b $ b

  var  var1 = {}; 

function function1()
{
// 调用weservice成功重新调整json数据
return 数据;
};

function function2()
{
var var1 = function1();

alert( show username: + var1.UseName); // 现在我在警报框中收到不应答错误
}

解决方案

您的代码问题似乎与异步操作延迟有关。当您调用 function1()并期望在 var1 中获得结果时,您将在成功后获得结果在 function1()中完成您的Web服务调用。

但是您的 alert()在从异步调用实际返回任何数据之前调用,因此你得到未定义的错误。



因此解决方案是调用警报()异步操作成功完成后。例如,使用jQuery调用您的Web服务并适当地分配成功和失败回调:



 


.ajax({
类型:POST,
url:'Web Service Url',
data:JSON.stringify(Data),
contentType:'application / json; charset = utf-8',
dataType:'json',
success:function(result){alert(show username:+ result.UserName);},
error:function (e){}
});





我希望你能正确理解这一点。 :)


I have a function which is return the JSON object, i am calling this function into another function.
in second function didn't read the first json object and getting undefined error in javascript.

var var1={};

function function1()
{
//calling weservice retuning the json data successfully 
return data;
};

function function2()
{
var var1= function1();

alert("show username :" +var1.UseName);  //now here i am getting the undefiend error in alert box
}

解决方案

The problem with your code seems to be related with async operation delay. When you call function1() and expect to get the result in var1 then you will get the result only after the successful completion of your web service call in function1().
However your alert() is being called before any data is actually returned from the async call and hence you get undefined error.

So the solution is to call the alert() when your async operation has been completed successfully. For example use jQuery to call your web service and assign success and failure callbacks appropriately:


.ajax({ type: "POST", url: 'Web Service Url', data: JSON.stringify(Data), contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (result) { alert("show username :" + result.UserName); }, error: function (e) { } });



I hope you are understanding this correctly. :)


这篇关于函数返回json并想调用另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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