简体   繁体   English

无法使用Ajax读取php文件输出

[英]Can't read php file output with ajax

I'm trying to submit a variable from a form to an ajax request of a php file, and output the contents of the php file to a div. 我正在尝试从表单向php文件的ajax请求提交变量,并将php文件的内容输出到div。

Here's my main file: 这是我的主文件:

<div>
    <form name="zipform">
        <p style="color:#cccccc;">Enter your Zipcode: <br><input type="text" name="zipcode">
            <input type ="Button" Value="Search Providers" onClick="showAndClearField(this.form)">
        </p>
    </form>
</div>
<div id="result"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function showAndClearField(frm)
{
var zip = frm.zipcode.value;
    frm.zipcode.value = "";

    $.ajax({
        url: "testphp.php?zipcode="+zip,
        success: function (data) {
            document.write("content of the executed page: " + data);
            $("#result").html(data);
        },
        error: function (xhr, status, error) {
            if (xhr.status > 0) document.write("got error: " + status);
        }
    });
}
</script>

Here's the testphp.php file: 这是testphp.php文件:

<?php
$zipcode = $_GET["zipcode"];
echo '<div><p>'.$zipcode.'</p></div>';
?>

The above results in a blank page of "got error: error" 上面的结果导致空白页出现“错误:错误”

What am I doing wrong? 我究竟做错了什么?

You can just do.. 你可以做..

<?php

 if (isSet ($_GET ['zipcode']))
 {
    $zipcode = $_GET["zipcode"];
    echo '<div><p>'.$zipcode.'</p></div>';
    exit;
 } 
?>

html html

<div>
    <form name="zipform">
    <p style="color:#cccccc;">Enter your Zipcode: <br><input type="text" name="zipcode" id='zipcode'>
        <input type ="Button" Value="Search Providers" id="getZip">
    </p>
    </form>
</div>
<div id="result"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>

$(document).ready (function (){

    $("#getZip").on ("click", function (e){
        var zip = $("#zipcode").val ();

        $.ajax({
            url: "test1.php",
            data: {zipcode: zip},
            type: "GET",

            success: function (d) {
                document.write("content of the executed page: " + d);
                $("#result").html(d);
            },

            error: function (xhr, status, error) {
                if (xhr.status > 0) document.write("got error: " + status);
            }
        });

        e.preventDefault;
    });
 });
</script>

Kinda my way of doing it, yet it works wonders. Kinda是我的操作方式,但效果不错。

try $.get 尝试$.get
this is easier 这比较容易

$.get(
   'testphp.php',{'zipcode':zip}
).done(function(data)
{
$("#result").html(data);
})

you want send get method without var 你想发送不带var的get方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM