从服务器向Javascript(客户端)发送信息 [英] send information from server to Javascript (client)

查看:106
本文介绍了从服务器向Javascript(客户端)发送信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好b $ b

我的javascript代码从服务器获取一些信息



javacode:

Hi
my javascript code gets some info from the server

javacode:

CallGenerateIDHandler();




function CallGenerateIDHandler() {
    $.ajax({
        url: "GenerateID.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: { 'Type': 'ID' },
        responseType: "json",
        success: OnComplete,
        error: OnFail
    });
    return false;
}
function OnComplete(result) {
    alert([result.Id]);
}
function OnFail(result) {
    alert('Request failed');

}







the

alert([result.Id]);

提醒我想要的结果但是如何返回此值而不是

alert me the result I want but how can I return this value instead of

return false;

推荐答案

.ajax({
url:GenerateID.ashx,
contentType:application / json; charset = utf-8,
dataType:json,
数据:{'Type':'ID'},
responseType:json,
成功:OnComplete,
错误:OnFail
});
返回false;
}
函数OnComplete(结果){
alert([result.Id]);
}
函数OnFail(结果){
alert('Request failed');

}
.ajax({ url: "GenerateID.ashx", contentType: "application/json; charset=utf-8", dataType: "json", data: { 'Type': 'ID' }, responseType: "json", success: OnComplete, error: OnFail }); return false; } function OnComplete(result) { alert([result.Id]); } function OnFail(result) { alert('Request failed'); }







the

alert([result.Id]);

提醒我想要的结果,但我怎么能返回这个值而不是

alert me the result I want but how can I return this value instead of

return false;


好了我现在好了看到它:)。



你的问题是你正在进行异步操作的ajax调用,这就是为什么有一个回调(OnComplete / OnFail)函数,在你收到你的回复/错误后调用。



所以你不能从CallGenerateIDHandler()返回值;因为这个函数是同步运行的。



你能做的就是在你的OnComplete函数中保存一些元素/ localstorage的值。然后打电话来处理它。



你究竟想做什么?



另一种解决方案是make同步通话。你现在有同样的事情,但是添加

async:false,



注意:

这样就可以了对你而言,但这种方法的问题在于它会阻止你的UI线程,所以在你得到回复之前,页面不会响应。这是非常重要的一点!
Ok now I see it :).

Your problem is that you are making ajax call which is asynchronous operation, that is why there is a callback(OnComplete/OnFail) function that is called after you get your response/error back.

So you can't return the values from CallGenerateIDHandler(); because this function runs synchronously.

What you can do is save value to to some element/localstorage in you OnComplete function. And then call process it.

What exactly are you trying to do?

Another solution is make synchronous call. same thing you have now but add
async:false,

Note:
This is going to work for you, but the problem with this approach is that it will block you UI thread so page will not respond until you get response back. That is very important thing to mention!


这篇关于从服务器向Javascript(客户端)发送信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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