2016-01-25 111 views
1

當我在JQuery代碼的主體中調用Ajax時,它返回正確的結果,但是當我從函數內部調用它時,它失敗。下面是服務器端代碼:在函數內調用時Ajax失敗

<?php 
 
    $what  = $_POST["what"]; 
 
    $where  = $_POST["where"]; 
 

 
    if(isset($what)){ 
 
     $data = array(
 
      "what"  => $what, 
 
      "where"  => $where, 
 
     ); 
 
     echo json_encode($data); 
 
    } 
 
    ?>

下面是成功(返回文本瀏覽器)的代碼:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
    <html> 
 
     <head> 
 
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> 
 
      <script type="text/javascript"> 
 

 
      what = "dog"; 
 
      where = "in the manger"; 
 

 
      $.ajax({ 
 
       url: "test.php", 
 
       type: "POST", 
 
       data: {what : what, where : where}, 
 
       dataType: "json", 
 
       success: function (data) 
 
       { 
 
        $("#result").text(JSON.stringify(data)); 
 
       }, 
 
        error: function (error) 
 
       { 
 
        alert("ajax error "); 
 
       } 
 
      }); 
 

 
      </script> 
 
     </head> 
 
     <body> <div id="result"></div> </body> 
 
    </html>

,這裏是代碼失敗(提醒「錯誤」): `

<html> 
 
    <head> 
 
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
     <script type="text/javascript"> 
 

 
      what = "dog"; 
 
      where = "in the manger"; 
 

 
      function get_click() { 
 
      $.ajax({ 
 
       url: "test.php", 
 
       type: "POST", 
 
       data: {what : what, where : where}, 
 
       dataType: "json", 
 
       success: function (data) 
 
       { 
 
        $("#result1").text(JSON.stringify(data)); 
 
       }, 
 
       error: function (error) 
 
       { 
 
        alert("ajax error " + JSON.stringify(error)); 
 
       } 
 
      }); 
 
      } 
 
     </script> 
 
    </head> 
 

 
    <body> 
 
     <div id="result1"></div> </body> 
 
     <form onsubmit="get_click()"> 
 
      <input type="submit"> 
 
     </form> 
 
    </body> 
 
    </html>

我想使功能包裹的Ajax調用工作,因爲我需要它發送到服務器之前處理來自表單的數據。我在做什麼錯誤?

環境是一個無頭的樹莓派與Raspbian操作系統,在Windows 10

+0

我看到幾個問題開始。 1)你連接jquery兩次。 2)你的jQuery鏈接之一是在html開頭之上。 –

回答

2

它出現的機率FireFox瀏覽器,你沒有看到在瀏覽器中的任何文本的原因是,你提交一個表單,你不會阻止表單提交的默認操作。這會導致ajax調用被髮送,但是這個頁面會立即重新加載,並且不會顯示ajax調用的結果。

要解決這個問題,您可以在事件處理函數中調用e.preventDefault()

function get_click(e) { 
    e.preventDefault(); 
    $.ajax({ 
     url: "test.php", 
     type: "POST", 
     data: {what : what, where : where}, 
     dataType: "json", 
     success: function (data) { 
      $("#result1").text(JSON.stringify(data)); 
     }, 
     error: function (error) { 
      alert("ajax error " + JSON.stringify(error)); 
     } 
    }); 
} 

而且,事件參數添加到您的HTML:

<form onsubmit="get_click(event)"> 
     <input type="submit"> 
    </form> 

工作演示:https://jsfiddle.net/jfriend00/841v9rpf/。如果您從演示中刪除e.preventDefault(),則表單將提交。

+0

是的!非常感謝,朋友。 – Sid