3

因此,在尝试让 javascript 使用 Ajax 将值传递给 php 脚本时,我收到以下错误消息。

未捕获的 SyntaxError:输入意外结束

在单步执行代码时,我发现我的脚本响应返回了一个空字符串。有人请指出我的错误,我似乎无法掌握它。

这是我的 javascript (request.js)

var request;

function getHTTPObject()
{
    var xhr = false;
    if (window.XMLHttpRequest)
    {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try
        {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                xhr = false;
            }
        }
    }
    return xhr;
}

function runAjax(JSONstring)
{
    // function returns "AJAX" object, depending on web browser
    // this is not native JS function!
    request = getHTTPObject();
    request.onreadystatechange = sendData;
    request.open("GET", "request.php?json="+JSONstring, true);
    request.send(null);
}

// function is executed when var request state changes
function sendData()
{
    // if request object received response
    if(request.readyState == 4)
    {
    // parser.php response
    var JSONtext = request.responseText;

    // convert received string to JavaScript object
    var JSONobject = JSON.parse(JSONtext);


    // notice how variables are used
    var msg = "Number of errors: "+JSONobject.errorsNum+
        "\n- "+JSONobject.error[0]+
        "\n- "+JSONobject.error[1];

    alert(msg);
    }
}

我的 php 文件。

<?php
//request.php
$decoded = json_decode($_GET['json']);

$json = array(
    'errorsNum'    =>    2,

    'error'       =>    array(
                        "error 1","error 2!"
                 )
);

$encoded = json_encode($json);

die($encoded);

?>

最后是我调用 ajax 的 html 文件。

<html>
<head>
<script src="request.js">
</script>
</head>
<body>
<a href="Javascript:runAjax('vinoth')">call</a><br>
</body>
</html>

提前致谢。

4

0 回答 0