2011-09-20 86 views
0

我正在使用jquery的帖子,不知何故,似乎該帖子發佈兩次。我正在Android Broswer上測試這個。非常有線。有人知道爲什麼嗎?這是一個jQuery的bug或什麼?jquery發佈兩次?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <script type="text/javascript" src="vendor/jquery-1.5.js"></script> 
    <title>Test Runners</title> 
</head> 
<body> 

<h1>Test Runner</h1> 
<script type="text/javascript"> 
    post_result = function() { 
     console.log("post_result is called!"); 
     $.post('http://192.168.2.3:8001', { 'jasmine-url' : "test url" ,'jasmine-content' : "test content" }) 
      .success(function() { alert("second success"); return true; }) 
      .error(function() { alert("error"); return true; }) 
      .complete(function() { alert("complete"); return true; }); 
    } 
</script> 
<a href="javascript:post_result()">post result</a> 
</body> 
</html> 

更多信息:

做了一些改動原來的職位。

實際上,在我們第一次發佈post請求時,它只發出了兩個請求,一個是OPTION方法,另一個是POST。

但是在Android瀏覽器中,每次同一個代碼都會發兩個POST請求。我認爲使用Android瀏覽器的JQUERY可能存在問題。任何人都知道這一點?

+1

顯示執行2個請求的Chrome開發人員工具的屏幕快照 – zerkms

+0

我最近遇到了一些問題(廣泛報道),Chrome會令人驚訝地發出多個GET(空白'src'是一個示例),但從未使用POST。同意@zerkms,需要更多。 – Dan

回答

2

不知道爲什麼它會發布兩次,但我注意到與您的代碼的幾個問題。

首先,我們很早就通過內聯JavaScript並在href內部執行JavaScript--屬性是一個很大的不是的(這裏有onclick屬性,但那是另一個你不應該觸摸的恐龍)。有很多優秀的JavaScript框架可以讓它很容易綁定到事件上,比如點擊。

其次,你的post_result函數被定義爲全局的並且缺少分號。

要糾正上述情況,應在頭部或單獨的文件中放入以下片段。它也會做同樣的事情,但採用更好的做法採用更加jQuery的方式。

的JavaScript

// Short-hand for DOM-ready 
$(function(){ 
    // Define variable in local scope to store request 
    var request; 

    // Bind to the click event to all anchors with the class post-results 
    $("a.post-results").click(function(e){ 
     // Prevent default behavior. I.e. stop browser from navigating 
     e.preventDefault(); 

     // If there's a previous request, abort it. No need for two. 
     // You could also return here if you want to wait for the first 
     // one to finish. 
     if (request) { request.abort(); } 

     // Let's fire off the request and store it for future reference 
     request = $.post(
       'http://192.168.2.3:8001', 
       { 
        "jasmine-url": "test url", 
        "jasmine-content": "test content" 
       } 
      ) 
      .success(function(res) { 
       console.log("second success", res); 
      }) 
      .error(function(xhr, err) { 
       console.log("error", err); 
      }) 
      .complete(function() { 
       console.log("complete"); 
       // Set request var to null 
       request = null; 
      }); 
    }); 
}); 

HTML

<a class="post-results" href="#">Post result</a> 

爲了確保jQuery是正確加載,你應該從建立公共CDN加載它如Google Libraries API

我也催促你跳轉到向後兼容HTML4的HTML5文檔類型。只需將您的文檔類型切換爲<!DOCTYPE html>即可。

+0

非常感謝Marcus! – dongshengcn

+0

我不同意'onclick'。特別是,有一些jQuery UI插件基本上以一種綁定到原始文件的方式重寫了一些DOM元素,但是「onclick」仍然有效。 – Dan