AJAX没有正确回应

时间:2015-09-17 09:02:16

标签: javascript php ajax

我已经为在线食品店制作了一个AJAX代码,但是当我运行它时,它没有显示正确的输出,即弹出一个说出错的东西总是弹出。我想知道我的代码中的问题是什么,它是否与连接处理程序或JS脚本有关

这是我的index.php代码

<!DOCTYPE html>
<HTML>
    <HEAD>
        <TITLE>AJAX</TITLE>
        <SCRIPT type = "text/javascript" src = "JS/store.js"></SCRIPT>
    </HEAD>
    <BODY onload = "process()">
        <H3>Foodstore</H3>
        Enter the food you would like to order:
        <INPUT type = "text" id = "user_input" placeholder = "Food Item" />
        <DIV id = "output_area" />
    </BODY>
</HTML>

这是我正在使用的JS代码

var XML_HTTP = create_XML_HTTP_request_object();
function create_XML_HTTP_request_object() {
    var XML_HTTP;
    if(window.ActiveXObject) {
        try {
            XML_HTTP = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            XML_HTTP = false;
        }
    } else {
        try {
            XML_HTTP = new XMLHttpRequest();
        } catch(e) {
            XML_HTTP = false;
        }
    }
    if (! XML_HTTP) {
        alert('Cant create the object!!');
    } else {
        return XML_HTTP;
    }
}
function process() {
    if((XML_HTTP.readyState == 0) || (XML_HTTP.readyState == 4)) {
        food = encodeURIComponent(document.getElementById("user_input").value);
        url = "process.php?food=" + food;
        XML_HTTP.open("GET", url, true);
        XML_HTTP.onreadystatechange = handle_server_response;
        XML_HTTP.send(null);
    } else {
        setTimeout('process()', 1000) ;
    }
}
function handle_server_response() {
    if(XML_HTTP.readyState == 4) {
        if(XML_HTTP.status == 200) {
            XML_response = XML_HTTP.responseXML;
            XML_document_element = XML_response.documentElement;
            message = XML_document_element.firstChild.data;
            document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>';
        } else {
            alert('Something went wrong!!');
        }
    }
}

这是我正在使用的PHP代码

<?php
    header('Content-Type: text/xml');
    echo '<?XML version = "1.0" encoding = "UTF-8" standalone = "yes" ?>';
    echo '<response>';
        $food = $_GET['food'];
        $food_array = array('tuna' , 'bacon' , 'loaf' , 'cheese' , 'pizza') ;
        if(in_array($food , $food_array)) {
            echo 'We do have ' . $food . ' !!';
        } elseif($food == '') {
            echo 'Enter a food item';
        } else {
            echo 'Sorry we don\'t sell ' . $food . ' !!';
        }
    echo '</response>';
?>

2 个答案:

答案 0 :(得分:0)

作为您发布的ajax功能的替代方案,请考虑以下事项:

    function _ajax( url, options ){
        var factories=[
            function() { return new XMLHttpRequest(); },
            function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
            function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
            function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
            function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
            function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
            function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
        ];
        /* Try each factory until we havea winner */
        for( var i=0; i < factories.length; i++ ) {
            try { var req = factories[ i ](); if( req!=null ) { break; } }
            catch( err ) { continue; }
        };

        var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
        var callback=options.hasOwnProperty('callback') ? options.callback :false;

        if( !callback ){
            alert( 'No callback function assigned' );
            return false;
        }

        var headers={
            'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
            'Content-type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest'
        };

        /* The main parameters of the request */
        var params=[];
        if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
            for( var n in options.params ) params.push( n + '=' + options.params[n] );
        }

        /* Additional arguments that can be passed to the callback function */
        var args=options.hasOwnProperty('args') ? options.args : {};

        /* Assign callback to handle response */
        req.onreadystatechange=function(){
            if( req.readyState ) {
               if( req.status==200 ) options.callback.call( this, req.response, args );
               else console.warn( 'Error: '+req.status+' status code returned' );
            }
        }

        /* Execute the request according to desired method */
        switch( method ){
            case 'POST':
                req.open( method, url, true );
                for( header in headers ) req.setRequestHeader( header, headers[ header ] );
                req.send( params.join('&') );
            break;
            case 'GET':
                req.open( method, url+'?'+params.join('&'), true );
                for( header in headers ) req.setRequestHeader( header, headers[ header ] );
                req.send( null );
            break;  
        }
    }

然后您可以像这样使用它:

function process(){
    call _ajax( this, 'process.php', { 'method':'get', 'callback':handle_server_response, params:{ 'food':food } } );
}

function handle_server_response(response){
    try{/* this is not tested! */
        var XML_document_element = response.documentElement ;
        var message = XML_document_element.firstChild.data ;
        document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>' ;
    }catch(err){
        console.warn('oops, an error occurred: %s',err);
    }
}

对于将来的ajax请求,您只需要为_ajax函数提供不同的参数,而不是每次都重写。此外,不是弹出用户可能不理解的警告消息,而是将错误记录到控制台。

但是,如果没有特别需要使用XML,我个人建议使用JSON而不是XML。以编程方式读取和写入要容易得多,需要更少的字节进行传输,并且不太容易出现奇怪字符的异常情况。

答案 1 :(得分:0)

Firefox至少不喜欢处理指令

<?XML ... ?>

发出错误not well-formed ...可以正常使用

<?xml ... ?>

但是,虽然您的代码无法正常工作,但WONT会导致警报...您收到警报表明您的浏览器无法找到process.php(它应与您的HTML位于同一文件夹中)文件)

并添加了一个注释...... Edge不喜欢大写的HTML标签,它不会破坏,但它有一个关于它们的方式