失败的AJAX&;Localhost WAMP配置上的PHP通信


Failed AJAX & PHP communication on Localhost WAMP Configuration

首先,我是AJAX的新手,这是我第一次尝试将AJAX与PHP结合使用。我遇到的问题是,尽管我的XMLHttpRequest状态成功地将其状态更改为4,即:完成,但responseText和所有其他响应类型都是"(空)。

我已经尝试了非常简单的代码版本,最近还尝试了W3Schools AJAX&PHP示例http://www.w3schools.com/ajax/ajax_aspphp.asp它也没有归还任何东西。这让我相信这可能是一个配置问题,但我不知道该怎么办?有什么建议吗?

这是我的js的一部分,它适用于AJAX PHP Comms:

$("#submitButton").click(function() {
    alert("The button has been clicked")
    if(($("#title").val().length < 3 ) || ($("#description").val().length < 3 ))
    {
        alert("Title and Description must be 3 characters or more!");
    }
    else
    {
            var ajaxRequest;
            try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
            } catch (e){
                // Internet Explorer Browsers
                alert("THE PROBLEM WAS IE " + e);
                try{
                    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    alert("THE PROBLEM WAS second " + e);
                    try{
                        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e){
                        // Something went wrong
                        alert("Your browser broke!");
                        return false;
                    }
                }
            }   
            // receive data sent from the server
            ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                    // Get the data from the server's response
                    var test = ajaxRequest.responseText; 
                    alert(test);
                    //console.log(xmlHttp);
                    console.log(ajaxRequest);
                }
            }
            //Variables
            var title =$("#title").val();
            var description =$("#description").val();
            var url = $("#url").val();
            ajaxRequest.open('GET','http://localhost/TestPHP/Model/AddNewVideo.php');
            try {
                ajaxRequest.send();
            }
            catch(e) {
                alert("THE PROBLEM WAS " + e);
            }   
    }
});

这是我的PHP代码。PHP本身还没有经过测试以确保SQL查询有效,但如果我只是将其简化为回显"helloworld",它甚至都不起作用。

    <?PHP
header('Access-Control-Allow-Origin: *');
//Connect to dBase
include("mysql_connect.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo 'POSTed Method';
  }
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    echo 'GET Method';
  }

//Debugging
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
//Gather Variables
echo $title = mysql_real_escape_string($_GET["TITLE"]);
$description = mysql_real_escape_string($_GET["DESCRIPTION"]);
$url = mysql_real_escape_string($_GET["URL"]);
//Insert new query
mysql_query('INSERT INTO video VALUES($title, $description, $url') or die(mysql_error());

//Close the DBase
mysql_close($connect);
echo $description;
?>

使用JQuery的js的MyUpdate和增强版;

$("#submitButton").click(function(event) {
        alert("The button has been clicked")
        if(($("#title").val().length < 3 ) || ($("#description").val().length < 3 ))
    {
        alert("Title and Description must be 3 characters or more!");
    }
    else
    {
            // Variables to pass
            var $form = $("#AddVideoForm"),
            // Gather all fields 
            $inputs = $form.find("input, select, button, textarea"),
            // serialize the data in the form
            serializedData = $form.serialize();

            try
            {
                //JQuery Based AJAX HTTP Request
                $.ajax({
                    url: "http://localhost/TestPHP/Model/AddNewVideo.php",
                    type: "POST",
                    data: serializedData,
                    success: function(response, textStatus, jqXHR){
                    // Show success
                    alert("Wonderful It worked");
                    console.log("Hooray, it worked!");
                    },
                    // callback handler that will be called on error
                    error: function(jqXHR, textStatus, errorThrown){
                    // log the error to the console
                    console.log("The following error occured: "+ textStatus, errorThrown)
                    },
                    complete: function(){
                    // Display Completed message
                    alert("Totally Completed!  Hoorah!");
                    }
                });
            } 
            catch (e)
            {
                alert("THE PROBLEM WAS " + e);
            }
            event.preventDefault();
    }
});'

在评论中进行了几次交流后:答案:

$("#submitButton").click(function(event) {
    /* ajax request here */
    event.preventDefault();
});

原因是浏览器试图执行点击锚点或提交按钮时的正常行为(我不知道点击的元素)。preventDefault()用于停止正常执行。

有一件事需要注意。请对Ajax请求使用jQuery。上面完成ajax请求的所有代码逻辑都已经在jQuery框架上完成了,您可以从20多行代码变成几行代码。