簡體   English   中英

提交到PHP時出現AJAX錯誤

[英]Getting an AJAX error when submitting to PHP

我有一個基本表單,其中提交了Facebook朋友的ID,而php返回我的名字,FB照片,朋友的名字和朋友的fb照片。 這是我的相關代碼

的HTML

<form name="input">
<input type="text" name="name" id="name"/>
<input id="submit" type="submit" class="btn btn-info" value="Submit"/>
</form>

<div class="row" id="graphArea"></div>

JAVASCRIPT

$('#submit').click(function(e){
    e.preventDefault();
    var formData = $('form').serialize();
    submitForm(formData);
});

function submitForm(formData){
$.ajax({    
    type: 'POST',
    url: 'graph.php',        
    data: formData,
    dataType: 'json',
    cache: false,
    timeout: 7000,
    success: function(data) { 
        $("#graphArea").load("graph.php");
        $(window).scrollTop($("#graphArea").offset().top);
        $("#graphArea").fadeIn(500);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error");          
    },              
    complete: function(XMLHttpRequest, status) {            

        $('form')[0].reset();
    }
});

graph.php

<?php
    require 'resources/plugin/facebook-php-sdk/src/facebook.php';
    //..some facebook authentication stuff
    $friend = $_POST['name'];
    $basicInfo = $fb->api('me?fields=friends.uid(' . $friend . ').fields(first_name,name),first_name,name');
 ?>
<hr>
<br />
<div class="span2 offset2"><h3>
<?php
    echo $basicInfo['name'] . "</h3></div><div class=\"span2\">";
    echo "<img src='https://graph.facebook.com/" . $user . "/picture?type=large'>";
    echo "</div><div class=\"span2\">";
    echo "<img src='https://graph.facebook.com/" . $friend . "/picture?type=large'></div>";
    echo "<div class=\"span2\"><h3>" . $basicInfo['friends']['data'][0]['name'];
?>
</h3>
</div>

每次提交表單時,我都會收到錯誤部分,它會在其中提示“發生錯誤”。 但是,通過Google Chrome Javascript控制台瀏覽,然后單擊“網絡”,然后單擊“預覽”,我看到了想要的結果! 這是我第一次接觸PHP和AJAX,我將很高興獲得所有幫助。 謝謝!

在您的javascript ajax調用中,您將其指定為dataType: 'json',然后從php返回html這將引發錯誤。 如果您希望響應使用html格式,請將數據類型更改為html

您對graph.php ajax調用包含dataType: 'json' ,但是graph.php似乎輸出了HTML片段。 另外,您的AJAX成功處理程序再次調用graph.php ,這是不必要的,因為您剛剛調用了graph.php來提交表單。 您應該取回返回的HTML並將其注入DOM:

$.ajax({    
    type: 'POST',
    url: 'graph.php',        
    data: formData,
    // REMOVED dataType
    cache: false,
    timeout: 7000,
    success: function(data) { 
        $("#graphArea").html(data);   // CHANGED
        $(window).scrollTop($("#graphArea").offset().top);
        $("#graphArea").fadeIn(500);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error");          
    },              
    complete: function(XMLHttpRequest, status) {            

        $('form')[0].reset();
    }
});

暫無
暫無

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

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