Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript对象内部的Ajax异步_Javascript_Jquery_Ajax_Oop_Asynchronous - Fatal编程技术网

javascript对象内部的Ajax异步

javascript对象内部的Ajax异步,javascript,jquery,ajax,oop,asynchronous,Javascript,Jquery,Ajax,Oop,Asynchronous,我正在构建一个javascript对象,用于处理ajax功能错误处理和响应。我的问题是,只有在ajax请求中设置async:false时,它才起作用。在其他任何情况下,结果都是未定义的。这里还有一些人建议,使用async:false是一件坏事。所以我的问题是:我是否可以重写代码以避免使用async:false,而不为此添加大量行 {extends file="full.tpl"} <!-- SMARTY STUFF --> {block name=content} <!-- S

我正在构建一个javascript对象,用于处理ajax功能错误处理和响应。我的问题是,只有在ajax请求中设置async:false时,它才起作用。在其他任何情况下,结果都是未定义的。这里还有一些人建议,使用async:false是一件坏事。所以我的问题是:我是否可以重写代码以避免使用async:false,而不为此添加大量行

{extends file="full.tpl"} <!-- SMARTY STUFF -->
{block name=content} <!-- SMARTY STUFF -->
<script type="text/javascript">  
function contentManager(options){

   this.O = options; // var for options
   this.Q; // var for the ajaxresponse
   this.R; // var for the ajaxresponse object JSON.parse(response);

   this.SetupPost = function(){ //[#3] Method which loads the Ajax method
      this.Q = this.AjaxPost(); //[#4] Pass the AjaxPost() return response to this.Q
      this.Q.done(function(response){
         this.R = JSON.parse(response); //[#5] Convert the result to Object
      });
      return this.R; //[#6] Return the result object
   },

   this.AjaxPost = function(){
      return $.ajax({
            type: "POST",
            url: this.O.output_url,
            dataType: this.O.datatype,
            async: false,
            context: this
      });
   },

}

var details = { //Object for parameters - will use inside the contentManager object
           output_url: '{$base}gallery/ajaxadd/', //url uf the ajax call
           data: $(document.getElementById('gallery_name')).serialize(), //data what we want to post (i dont use it now)
           dataType: 'json', //datatype
           output_area: 'apple', //where to put the results if there are any
           errorMsg: { //where to put the error messages if there are any
               Visible: true, //visibility
               Area: 'top' //area to put error messages
           }  
}; // details WILL GO INSIDE contentManager ->> see below

$( document ).ready(function() { //evrything has been loaded
        var cm = new contentManager(details); //[#1] create the object(contentManager) AS (cm) when the page loads
        var result = cm.SetupPost(); //[#2] call the SetupPost method (will return an object, containing the results(object))
        console.log(result); //--> console.log the result object //[#7] There must be the object, but i get only 'undefined', when i dont use the async: false.

});  
</script>
<div id="testarea">
   <form id="testform"> </form>
   <input type="text" name="gallery_name" value="asdasd" id="gallery_name" class="form-control" placeholder="Gallery Name">
</div>
{/block} <!-- SMARTY STUFF -->
使用Promise通常是进行异步调用的一种更简单的方法。 看看这个函数:

function callService(url, args) {
    return new Promise(
        function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.onload = function() {
                var value = xhr.responseText;
                try {
                    resolve(JSON.parse(value));
                }
                catch (ex) {
                    reject("Invalid JSON!");
                }
            };
            xhr.onerror = function() {
                reject("Connexion problem: " + xhr.statusText);
            };
            xhr.open("POST", url, true);
            var params = encodeURIComponent(args);
            xhr.setRequestHeader(
                "Content-type",
                "application/x-www-form-urlencoded");
            xhr.send(params);
        }
    );
}
您可以这样使用它:

callService("http://mywebsite/service.php", "a=6&x=test").then(
    function(data) {
        console.log(data);
    },
    function(err) {
        alert(err);
    }
);
var cm = new contentManager(details)
cm.SetupPost(function (result) {
    console.log(result);
});
Promise是现代主流浏览器的一部分。它不是一个外部库。你可以直接使用它


这对您的问题有帮助吗?

您应该传递回调,该回调将在请求完成后调用

this.Q.done(function(response){
   this.R = JSON.parse(response);
});
return this.R; //[#6] Return the result object
当您返回R时,它是未定义的,因为传递给done的函数尚未被调用。你可以这样写短信

this.SetupPost = function(callback){ 
   var req = this.AjaxPost(); 
   req.done(function(response){
      callback(JSON.parse(response)); //invoke your callback
   });
},
然后像这样使用:

callService("http://mywebsite/service.php", "a=6&x=test").then(
    function(data) {
        console.log(data);
    },
    function(err) {
        alert(err);
    }
);
var cm = new contentManager(details)
cm.SetupPost(function (result) {
    console.log(result);
});

是的,绝对是!谢谢,我也会尝试这个版本。谢谢,我会这样尝试: