简体   繁体   English

包含ajax的javascript函数在提交后不起作用,但与按钮单击事件一起起作用

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

it is strange. 它很奇怪。 I have a function with ajax that works great: 我有一个使用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){

when I call this function from a form submit event, any way, I get error function of ajax. 当我从表单提交事件调用此函数时,无论如何,我都会得到ajax的错误函数。

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

BUT if I call this function with button click event its works and get success() 但是,如果我使用按钮单击事件调用此函数,则该函数起作用并获得成功()

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

what you think about this? 您对此有何看法?

On form submit event you have to stop its default behavior using preventDefault() otherwise post back will occur and that could be reason of error. 在表单提交事件中,您必须使用preventDefault()停止其默认行为,否则将发回邮件,这可能是错误的原因。

Pass current element reference to the function using searchProduct(this) and in the function use preventDefault() like this: 使用searchProduct(this)将当前元素引用传递给函数,并在函数中使用preventDefault()如下所示:

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

Jquery: 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();

}

Form submit will actually send a HttpRequest to the web server, I wonder why do you want to send an AJAX request along with that. 表单提交实际上会将一个HttpRequest发送到Web服务器,我想知道为什么您要同时发送AJAX请求。

OnClick will be simple event you can use it to trigger AJAX request, it will not send any other HttpRequest to the server. OnClick将是一个简单的事件,您可以使用它来触发AJAX请求,它不会将任何其他HttpRequest发送到服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM