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条)

报告相同问题?

悬赏问题

  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用