在php函数之后从javascript获取隐藏的字段值

时间:2017-02-09 11:34:07

标签: javascript php ajax hidden-field

我的代码遇到了一些麻烦。我的页面中有一个Javascript函数和一个填充隐藏字段的PHP函数。当我从Javascript中读取隐藏字段时,读取的值不是当前值。好像没有刷新。 我需要帮助。每个提示真的很感激! 谢谢!

这是我的Javascript代码:

var username = document.getElementById('user').value;
checkUserName(username);

var opennextpage = document.getElementById('hidden_field_openpage').value;

if (opennextpage == 'YES'){
// open next page
}
else{
alert('Can't open page');
}

我通过AJAX调用PHP页面是这样的:

function checkUserName(username){
    var strURL  = "js/ax_checkusername.php?user="+ username; 
    var req = getXMLHTTP();

    if (req)
    {
        req.onreadystatechange = function()
        {
            if (req.readyState == 4)
            {
                // only if "OK"
                if (req.status == 200)
                {
                    document.getElementById('hidden_field_openpage').value = req.responseText;
                } 
                else 
                {
                    alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                }
            }
        }
    }
    req.open("GET", strURL, true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.send(null);
}

1 个答案:

答案 0 :(得分:0)

为什么不将两者结合起来,如下所示:

function checkUserName(username){
    var strURL  = "js/ax_checkusername.php?user="+ username; 
    var req = getXMLHTTP();

    if (req)
    {
        req.onreadystatechange = function()
        {
            if (req.readyState == 4)
            {
                // only if "OK"
                if (req.status == 200)
                {
                   if (req.responseText == 'YES'){
// open next page here itself
}
else{
alert('Can\'t open page');
};
                } 
                else 
                {
                    alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                }
            }
        }
    }
    req.open("GET", strURL, true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.send(null);
}

然后只需调用checkUserName(用户名)?