簡體   English   中英

jQuery Ajax發布到php無法打印響應

[英]jQuery Ajax post to php not printing response

我正在使用通過ajax將數據發布到php頁面的新方法,而不刷新頁面,但響應未打印到控制台。

注意:在真正使Ajax工作之前,我尚未收集要發送的表單數據。

HTML:

<form id="myForm" action="process.php" method="post">
      <input type="text" placeholder="Email" id="email" name="email">
      <span class="error">Email not entered</span><br />
      <input type="password" placeholder="Password" id="pword" name="pword">
      <span class="error">Password not entered</span><br />
      <input type="text" placeholder="First Name" id="fname" name="fname">
      <span class="error">First Name not entered</span><br />
      <input type="text" placeholder="Last Name" id="lname" name="lname">
      <span class="error">Last Name not entered</span><br />
      <input type="submit" value="Submit">
</form>

jQuery的:

$('#myForm').on('submit', function(e){e.preventDefault()});

var request = $.ajax({
    url         : 'process.php',
    method      : 'POST',
    data        : {name: 'Robert'},
    dataType    : 'html'
});

request.done(function(response){
    console.log(response);
});

request.fail(function(){
    console.log('fail');
});

PHP:

<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>

您的“提交”功能沒有執行任何操作。 您需要在其中包含ajax調用。

嘗試:

jQuery(document).ready(function ($) {

    $('#myForm').on('submit', function(e){

        e.preventDefault();

        $.ajax({
            url         : 'process.php',
            method      : 'POST',
            data        : {name: 'Robert'},
            dataType    : 'html'
        })
        .done(function(response){
            console.log(response);
        })
        .fail(function(){
            console.log('fail');
        });
    });

});

另外我也不知道你在哪里加載JS。 但是您可能希望將其包裝在文檔就緒函數中,以確保您的表單在調用時存在。

最后,還有一個非常不錯的表單插件,可以使您輕松完成此工作。 JQuery.Form。

http://malsup.com/jquery/form/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM