开发者

Passing variable to callback after Ajax request

Is there a more elegant way of passing a variable after performing an Ajax request (JS->PHP) other than printing the results?

Printing ca开发者_如何学编程n get a little messy and also doesn't offer a lot of flexibility in terms of the return value (e.g. hard to pass objects).

Also, I had this random space that was printed in one of my Ajax request callbacks and I could not figure out where it came from. This problem would not exist with passing serialized variables or something like that, right?

Thanks in advance!


Pass attribute in form {url:"",method:"",data:{...},callback:function(){}}

In callback you can do a lot of stuff, google "javascript closures".

Hope this helps.

var ajax=function(){
  try{
    var xml       =new XMLHttpRequest();
    var args      =arguments;
    var context   =this;
    var multipart ="";

    xml.open(args[0].method,args[0].url,true);

    if(args[0].method.search(/post/i)!=-1){
      var boundary=Math.random().toString().substr(2);
      xml.setRequestHeader("content-type","multipart/form-data; charset=utf-8; boundary="+boundary);
      for(var key in args[0].data){
        multipart+="--"+boundary+"\r\ncontent-Disposition: form-data; name="+key+"\r\ncontent-type: application/octet-stream\r\n\r\n"+args[0].data[key]+"\r\n";
      }
      multipart+="--"+boundary+"--\r\n";
    }

    xml.onreadystatechange=function(){
      try{
        if(xml.readyState==4){
          context.txt=xml.responseText;
          context.xml=xml.responseXML;
          args[0].callback();
        }
      }
      catch(e){}
    }

    xml.send(multipart);
  }
  catch(e){}
}

If you want to get back response you can use this:

var response={}; ajax.call(response,{...args...})

and you can retrieve all data by response.txt or response.xml.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜