简体   繁体   English

如何从HTTPObject传递变量

[英]How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. 我是非常非常新的Javascript,以及一般的网络编程。 I think that I'm misunderstanding something fundamental, but I've been unable to figure out what. 我认为我误解了一些基本的东西,但我一直无法弄清楚是什么。

I have the following code: 我有以下代码:

function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
    if (userAuthHttpObject.readyState == 4) {
        var response = json.loads(userAuthHttpObject.responseText);
                    return response; //This is the part that doesn't work!
    }
};
userAuthHttpObject.send(params);

}

I would love to call it from my page with something like: 我很想从我的页面中调用它,例如:

var authResponse = checkUserAuth();

And then just do what I want with that data. 然后用这些数据做我想做的事。

Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called. 但是,返回一个变量只会将其返回给userAuthObject,而不是一直返回到最初调用的函数。

Is there a way to get the data out of the HttpObject, and into the page that called the function? 有没有办法从HttpObject中获取数据,并进入调用函数的页面?

Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. 使用AJAX需要围绕异步行为,这与其他类型的编程不同。 Rather than returning values directly, you want to set up a callback function. 您需要设置回调函数,而不是直接返回值。

Create another JavaScript function which accepts the AJAX response as a parameter. 创建另一个JavaScript函数,它接受AJAX响应作为参数。 This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever. 这个函数,我们称之为“takeAction(响应)”,应该做任何需要的事情,可能会打印失败消息或在隐藏字段中设置值并提交表单,无论如何。

then where you have "return response" put "takeAction(response)". 那么你有“返回响应”放“takeAction(响应)”。

So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();" 所以现在,takeAction会做你在调用“var authResponse = checkUserAuth();”之后所做的一切。

There are a couple of best practices you should start with before you continue to write the script you asked about 在继续编写您询问的脚本之前,您应该先了解一些最佳实践

  1. XMLHTTTPRequest() is not browser consistent. XMLHTTTPRequest()与浏览器不一致。 I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. 我建议你使用mootools这样的库或优秀的jquery.ajax作为起点。 it easier to implement and works more consistently. 它更容易实现,并且更加一致。 http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.ajax/

  2. content type is important. 内容类型很重要。 You will have have problems trying to parse json data if you used a form content type. 如果您使用表单内容类型,则在尝试解析json数据时会遇到问题。 use "application/json" if you want to use json. 如果你想使用json,请使用“application / json”。

  3. true user authorization should be done on the server, never in the browser. 真正的用户授权应该在服务器上完成,而不是在浏览器中完成。 I'm not sure how you are using this script, but I suggest you may want to reconsider. 我不确定你是如何使用这个脚本的,但我建议你可以重新考虑一下。

Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery: 开头的预备,这是我通过jquery从ajax调用到页面获取信息的一种方法:

$.ajax({
  //get an html chunk
  url: 'ajax/test.html',
  // do something with the html chunk
  success: function(htmlData) {
      //replace the content of <div id="auth">
      $('#auth').html(htmlData);

      //replace content of #auth with only the data in #message from 
      //the data we recieved in our ajax call
      $('#auth').html( function() {
          return $(htmlData).find('#message').text();
      });
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM