【问题标题】:How do I get my jQuery and PHP to work together with ajax?如何让我的 jQuery 和 PHP 与 ajax 一起工作?
【发布时间】:2012-10-30 00:03:34
【问题描述】:

我看到了一些类似的问题,但我还没有看到任何具体说明这一点的问题。我创建了一个非常简单的示例,我觉得它应该可以工作,但事实并非如此。重点是看到一些简单的东西,这样其他类似的东西就清楚了。

我觉得这很“基础”,很难简单得多;所以,人们应该能够支持它,知道它是终极的菜鸟垫脚石:

HTML 和 JS:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
    $("submit").click(function(){
        var req = $.ajax({
                type: 'POST',
                url: 'form.php',
                data: {
                        message: $('#message').val(),
                        author: $('#author').val()
                },
                timeout: 20000,
                beforeSend: function(msg) {
                        $("#sent").html(msg);
                }
        });

        req.fail(function(xhr, ajaxOptions, thrownError) {
                alert("AJAX Failed");
        });

        req.done(function(res) {
                 $("#received").html(res);
        });
    });
});
</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form>  
    Your message:  <input type="text" name="message" value="Hi!" /><br />
    Your name: <input type="text" name="author" value="Michael" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>

还有 PHP:

<?php 
  echo "The file is located at ".$_POST["message"].".<br>";
  echo "The file is named ".$_POST["author"].".";

【问题讨论】:

  • 它在做什么或不做什么?从外观上看,我怀疑它实际上是在提交表单并重新加载页面,而不是停止 ajax 请求。
  • @MichaelBerkowski 我正在更新其中的一些内容......截至目前,单击提交没有任何作用。我想要看到的是点击提交输出数据到#sent,然后到#received

标签: php jquery post


【解决方案1】:

您可以使用序列化而不是为输入字段分配 id:

<html>
<head>
<script type="javascript"></script>
<script type="text/javascript" src="/javascript/jquery-1.8.2.js">
$(document).ready(function(){
$("#submit").click(function(){
    var req = $.ajax({
            type: 'POST',
            url: 'form.php',
            data: $('#frm').serialize(),
            timeout: 20000,
            beforeSend: function(msg) {
                    $("#sent").html(msg);
            },
            success: function(data){
                alert('Success!Data was received by php.Message from the php script:'+data.res);
            }
    });

    req.fail(function(xhr, ajaxOptions, thrownError) {
            alert("AJAX Failed");
    });

    req.done(function(res) {
             $("#received").html(res);
    });
});});

</script>
</head>
<body>
<div id="sent"></div>
<div id="form">
<form id="frm">  
Your message:  <input type="text" name="message" value="Hi!" /><br />
Your name: <input type="text" name="author" value="Michael" /><br />
<input type="submit" id="submit" value="Submit me!" />
</form>
</div>
<div id="received"></div>
</body>
</html>

PHP 脚本:

<?php 
if(isset($_POST['message']) && isset($_POST['author']))
{
    $arr_to_pass_as_json = array('res'=>'This is your message:'.$_POST['message'].' and your author '.$_POST['author']);
    echo json_encode($arr_to_pass_as_json)
}
else
    echo json_encode(array('res'=>'Message and Author is required'));

我们使用 json 将结果从 php 显示到 javascript。希望这会有所帮助。

【讨论】:

  • 我仍然需要对此进行测试,但是从阅读代码来看,它看起来很棒。不过,请回答我;我可以在 keyup 中序列化吗?如果我这样做,服务器上的负载是不是更重了,因为我每次键入时都会发送整个表单,而不仅仅是一个字段的内容?
  • 是的..你可以在每个keyup中调用它。如果你有很多字段并且你的php脚本有很多事情要做(我的意思是一堆代码)会真正影响页面的加载时间.但是你可以给一个消息,比如“请稍候......”,你知道我的意思。
  • 先生,希望我的回答对您有所帮助。如果是这样,希望你给我的答案支票。谢谢^_^
  • 你说得很好!我已经测试了代码。我记得我确实需要进行一些编辑,但基本上它是有效的。
【解决方案2】:

用这个检查差异:

$(document).ready(function(){
    $("submit").click(function(){
        var req = $.ajax({
                type: 'POST',
                url: 'form.php',
                data: {
                        message: $('#message').val(),
                        author: $('#author').val()
                },
                timeout: 20000,
                beforeSend: function(msg) {
                        $("#sent").html(data);
                }
        })

        .fail(function(xhr, ajaxOptions, thrownError) {
                alert("AJAX Failed");
        })

        .done(function(res) {
                 $("#received").html(res);
        });
    });
});

检查这是否有效(根据http://api.jquery.com/jQuery.ajax/#jqXHR 应该)

【讨论】:

  • 其实这个不行。我对我应该使用 msg 还是 data 感到困惑......
【解决方案3】:

自从你使用

message: $('#message').val(),
author: $('#author').val()

您需要在输入 tgs 中指定您的 id。

<form>  
    Your message:  <input type="text" name="message" value="Hi!" id="message" /><br />
    Your name: <input type="text" name="author" value="Michael" id="author" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

您要求查找和 html id 选择器,并从中获取值,“名称”与 ID 不同。

或者,您可以在 html 表单中添加 id 并使用 .sezialize(),但在此步骤中简单地添加 id 会更简单。 http://api.jquery.com/serialize/

【讨论】:

  • 我应该使用.html(data)还是.html(msg),我应该使用("submit")还是("#submit")
猜你喜欢
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 2013-06-30
相关资源
最近更新 更多