简体   繁体   English

Ajax响应文本未在JavaScript中返回任何结果

[英]Ajax response text not returning any result in javascript

I know ajax is easy to use with jquery, but here I am trying to understand ajax with core javascript, I am sending two values name and age from index.html to indexPhp.php, In console it shows this message XHR finished loading: POST "http://localhost:8080/delPro/indexPhp.php". 我知道ajax很容易与jquery一起使用,但是在这里,我试图理解具有核心javascript的ajax,我将两个值的名称和年龄从index.html发送到indexPhp.php,在控制台中它显示此消息XHR finished loading: POST "http://localhost:8080/delPro/indexPhp.php". but it is not showing any result in div, here is html, js and php script 但它没有在div中显示任何结果,这是html,js和php脚本

<html>
<head>    
<link rel="stylesheet" type="text/css" href="style.css"/>
<script src="scripts.js"></script>
</head>        

<body>            
Name: <input type="text" id="name" name="name"><br><br>
Age:  <input type="text" id="age" name="age"><br><br>  
<button type="submit" value="Submit" onclick="showUser()">Submit</button>
<div id="resultDiv"></div>     
</body>        
</html>

Javascript 使用Javascript

function showUser() {

var hr = new XMLHttpRequest();
var url= "indexPhp.php";   
var name= document.getElementById("name").value;
var age= document.getElementById("age").value;    

var vars = {Name: name, Age: age};

hr.open("POST",url,true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.onreadystatechange = function(){

    if(hr.readyState == 4 && hr.status == 200){

        var return_data = hr.responseText;
        alert(hr.responseText);
        document.getElementById("resultDiv").innerHTML = return_data;
    }        
}
  hr.send(vars);

}

php script PHP脚本

if(isset($_POST['name']) && isset($_POST['age'])){

echo  $name = $_POST['name'] . " " . $age = $_POST['age'];    

}

Have you tried passing the data like this, 您是否尝试过像这样传递数据,

var vars = "Name="+name+"&Age="+age;

In your code you are sending the data as an object. 在代码中,您将数据作为对象发送。

Here is an ajax function I made sometimes ago. 这是我有时候做的ajax函数。 It can do both post and get and the use is just like you would use jQuery's ajax. 它既可以发布也可以进行获取,其使用就像您将使用jQuery的ajax一样。

function ajax(options, timeout){
    method = options.method || "POST";
    url = options.url || "#";
    (!timeout) ? timeout = 10000 : timeout = timeout * 1000; 
    var request, timedOut = false, xhrTooLong, datas = "";
    try{
        request = new XMLHttpRequest();
    } catch ( error ) {
        try {
            request = new ActiveXObject( "Microsoft.XMLHTTP" );
        } catch ( error ) {
            return true;
        }
    }
    if(options.data){
        for( dat in options.data){
            (datas == "")?datas+= (method.toLowerCase()=="get"?"?":"")+dat+"="+
               options.data[dat]:datas+="&"+dat+"="+options.data[dat];
        }
    }
    if(method.toLowerCase() == "get" && datas.length > 0)
        url = url + datas;
    request.open(method, url, true);
    request.onreadystatechange = function() {
        if( request.readyState == 1 ) {
            xhrTooLong = setTimeout(function(){
                if(request.readyState == 1){
                    timedOut = true;
                    request.abort();
                    if(options.aborted) options.aborted(true);
                }
            }, timeout);
        }
        if(request.readyState == 4 && !timedOut){
            window.clearTimeout( xhrTooLong );
            if(options.complete) options.complete (true);
            if ( /200|304/.test( request.status ) ) {
                if(options.success) options.success(request.responseText);
            } else {
                if(options.error) options.error(request.status);
            }
        }
    }
    request.setRequestHeader( 'If-Modified-Since', '06 Oct 1970 00:00:00 GMT' );
    if(method.toLowerCase() == "get"){
        request.send( null );
    } else {
        if(!options.contentType){
            request.setRequestHeader( 'Content-type','application/x-www-form-urlencoded; charset=UTF-8' );
        } else {
            request.setRequestHeader( 'Content-type',options.contentType );
        }
        request.setRequestHeader( 'Accepts', '*' );
        request.send( encodeURI( datas ) );
    }
    return false;
}

Now you can rewrite showUser like this: 现在,您可以像这样重写showUser:

function showUser() {

    var url= "indexPhp.php";   
    var name= document.getElementById("name").value;
    var age= document.getElementById("age").value;

    var vars = {Name: name, Age: age};

    ajax({
        url: url,
        method: "post",
        data: vars,
        success: function(result){
            alert(result);
            document.getElementById("resultDiv").innerHTML = result;
        },
        error: function(){ alert("Failed!") },
        aborted: function(){ alert("Aborted!") },
        complete: function(){ alert("Complete!") }
    });

}

You could also pass in an optional timeout in seconds after closing the function braces in the ajax call. 关闭ajax调用中的函数括号后,您还可以传入以秒为单位的可选超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM