du67560 2016-03-29 15:46 采纳率: 0%
浏览 64
已采纳

jQuery重用了ajax函数

So I'm trying to setup a website that uses PHP but has no PHP on it, so all of the PHP is bridged with AJAX and jQuery. So I'm trying to setup the user system to work on the same bases and to make things easier I want to have some jquery functions that get information from the database. Let's say a jQuery function that gets the first name of the logged in user:

function postData(dataString, url, type, callback){
var request = $.ajax({
    url: url,
    method: "POST",
    data: dataString,
    dataType: "JSONP",
    async: true,
    success: function(data){
        console.log("Server Responce: " + data.value);
        if(callback != null){
            return callback(data);
        }
    },
    error: function(jqHXR, textStatus){
        console.log("Server Error: " + textStatus);
    }
});
return request;
}

So for example sakes this is the function that runs the AJAX call. It is called as a variable which is request which returns nothing. I also have a call back however I don't want to use this all the time if it's avoidable. Below you can see what I want to be able to do.

function getFirstName(userId){
    return postData("userId=" + userId, "getFirstName.php", "GET", null);
}

function useFirstName1(userId){
    rndElement.innerHTML = getFirstName(userId);
}

function useFirstName2(userId){
    rndElement2.innerHTML = getFirstName(userId);
}

So as you can see I have one function which works with the AJAX function which is getFirstName and then I have two which depend on this function to retrieve the first name of the user useFirstName1 and userFirstName2. What I'm trying to achieve is away that when AJAX has got the JSON from the php file it sends it to the getFirstName function which would of called it and then that function returns it to it's own calling function.

Now I've read around and I'm sceptical that there is a solution to this problem and I'm going to need to rely on callback and make the same AJAX request multiple times in different scenarios. I'm not going to put async to false as this defeats the purpose of using AJAX in my opinion and we are all working to a faster more dynamic web and this doesn't help.

All I'm looking for is a simple yes (with guidance) or no whether I can do this or not. Thanks for taking the time to read.

  • 写回答

3条回答 默认 最新

  • douxi0098 2016-03-29 16:07
    关注

    A few changes... Basically, you need to leverage the fact that javascript is asynchronous and can use callbacks. Returning a value at the end of a function will often happen before the call within the body of the method has completed.

    function postData(dataString, url, type, callback){
        var request = $.ajax({
            url: url,
            method: "POST",
            data: dataString,
            dataType: "html",  // This needs to be html
            async: true,
            success: function(data){
                console.log("Server Response: " + data.value);
                // check that callback is a function and run it
                if (typeof(callback)=="function"){
                    return callback(data);
                }
            },
            error: function(jqHXR, textStatus){
                console.log("Server Error: " + textStatus);
            }
        });
        // do not return here because it will return before your asynchronous request
    }
    
    function getFirstName(userId, callback){
        return postData("userId=" + userId, "getFirstName.php", "GET", callback);
    }
    
    function useFirstName1(userId){
        getFirstName(userId, funciton(data){
            // most likely, for html requests, you'll get back responseText
            if (typeof(data.responseText)!="undefined") {
                rndElement.innerHTML = data.responseText;
                return true;
            }
    
            // well, maybe it returned xml
            if (typeof(data.responseXML)!="undefined") {
                rndElement.innerHTML = data.responseXML;
                return true;
            }
    
            // give up and just set the response data
            rndElement.innerHTML = data;         
        });
    }
    
    function useFirstName2(userId){
        getFirstName(userId, funciton(data){
            if (typeof(data.responseText)!="undefined") {
                rndElement2.innerHTML = data.responseText;
                return true;
            }
            if (typeof(data.responseXML)!="undefined") {
                rndElement.innerHTML = data.responseXML;
                return true;
            }   
            rndElement.innerHTML = data;
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大