1

首先,我是 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 查询正常工作,但如果我只是将其简化为 echo 'hello world',它甚至都不起作用。

    <?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 更新和增强版;

$("#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();
    }
});'
4

1 回答 1

0

在评论中交流了几句后: 答案:

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

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

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

于 2012-07-10T22:01:32.540 回答