php - Javascript 表单和对 PHP 的 Ajax 请求

标签 php javascript ajax

为什么这不起作用?当 Ajax 代码未包装在 function xmlhttpGet() 中时,它确实可以工作:PHP 返回被调用的页面并将其插入到 DIV 中。在此代码中,我将代码包装到函数 xmlhttGet() 中,但没有任何反应。请求的页面未加载到 DIV 中。

<html><head><title>AJAX GET </title>


</head><body><center />
<h1>Loading a web page into a DIV</h1>
<FORM id="form" method="post" action="">

<b> Enter argument: </b>
<input size="40" name="q" id="q" value="">
<INPUT TYPE="submit" id="submit" VALUE="Submit" onClick="xmlhttpGet(this.form)">
<INPUT TYPE="reset" VALUE="Reset">
</FORM>

<div id='info'>This sentence will be replaced</div>

<script>

function xmlhttpGet(form)
{

    nocache = "&nocache=" + Math.random() * 1000000
    request = new ajaxRequest()

    var $q = form.q.value

    request.open("GET", "urlget.php?url=amazon.com/gp/aw" + nocache, true)

    request.onreadystatechange = function()
    {
        if (this.readyState == 4)
        {
            if (this.status == 200)
            {
                if (this.responseText != null)
                {
                    document.getElementById('info').innerHTML =
                        this.responseText
                }
                else alert("Ajax error: No data received")
            }
            else alert( "Ajax error: " + this.statusText)
        }
    }

}// END xmlhttpGet

request.send(null) ;

function ajaxRequest()
{
    try
    {
        var request = new XMLHttpRequest()
    }
    catch(e1)
    {
        try
        {
            request = new ActiveXObject("Msxml2.XMLHTTP")
        }
        catch(e2)
        {
            try
            {
                request = new ActiveXObject("Microsoft.XMLHTTP")
            }
            catch(e3)
            {
                request = false
            }
        }
    }
    return request
}// ajaxRequest


</script></body></html>

[编辑]

onClick 触发正常。我已经通过将警报插入到函数中进行了验证。

[编辑2]

我想如果我也显示 PHP 位会有帮助

<?php // urlget.php

if (isset($_GET['url'])) {
    echo file_get_contents("http://".sanitizeString($_GET['url']));
}
else {
        echo "problem!" ; // [edited line]
    }

function sanitizeString($var) {
    $var = strip_tags($var);
    $var = htmlentities($var);
    return stripslashes($var);
}
?>

最佳答案

您必须在脚本中的某个位置调用 xmlhttp Get() 才能使其“运行”

关于php - Javascript 表单和对 PHP 的 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5503862/

相关文章:

javascript - JSLint 期望 'new' 而不是看到 '.'

javascript - ajax 我可以使用ajax发送一个在mysql中使用的变量执行一些查询然后将结果返回给我作为返回

jquery - json 问题(使用 zend 框架评估 ajax uploader )

php - Mysql表中记录消失了,如何查看是怎么回事?

php - 具有 Laravel 关系的 MySQL 嵌套集模型

php - 从 CSV 输出特定行

asp.net - 如何在 KeyUp 上进行文本框回发?

php - Symfony2 一次保存两个表单

javascript - 如何以类型安全的方式从 DOM 节点(而不是元素)获取属性?

javascript - Bootstrap 3 radio 需要双击