簡體   English   中英

包含ajax的javascript函數在提交后不起作用,但與按鈕單擊事件一起起作用

[英]javascript function containing ajax do not work after submit but work with button click event

它很奇怪。 我有一個使用ajax的功能,效果很好:

function searchProduct(){
var barcode=$.trim($('#barcode1').val());
$.ajax({
        type: 'GET',
        url: 'http://.............',
        data:{ 
            action: "search", 
            var: barcode, 
            },
        cache: false,
        datatype: 'json',
        success: function(output){

當我從表單提交事件調用此函數時,無論如何,我都會得到ajax的錯誤函數。

<form id="searchBox" name="searchBox" onsubmit="searchProduct()">

但是,如果我使用按鈕單擊事件調用此函數,則該函數起作用並獲得成功()

<span  class="tab-label" onclick="searchProduct()">Scan</span>

您對此有何看法?

在表單提交事件中,您必須使用preventDefault()停止其默認行為,否則將發回郵件,這可能是錯誤的原因。

使用searchProduct(this)將當前元素引用傳遞給函數,並在函數中使用preventDefault()如下所示:

<form id="searchBox" name="searchBox" onsubmit="searchProduct(this);">

jQuery:

function searchProduct(event){
var barcode=$.trim($('#barcode1').val());
$.ajax({
        type: 'GET',
        url: 'http://.............',
        data:{ 
            action: "search", 
            var: barcode, 
            },
        cache: false,
        datatype: 'json',
        success: function(output){
         }
      });

     event.preventDefault();

}

表單提交實際上會將一個HttpRequest發送到Web服務器,我想知道為什么您要同時發送AJAX請求。

OnClick將是一個簡單的事件,您可以使用它來觸發AJAX請求,它不會將任何其他HttpRequest發送到服務器。

暫無
暫無

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

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