简体   繁体   English

AJAX呼叫问题

[英]Issue with AJAX call

My AJAX call to a JSP works when called with drop down menu, but when called with the submit button the content disappears and the page refreshes. 使用下拉菜单调用时,我对JSP的AJAX调用有效,但是使用提交按钮调用时,内容消失并且页面刷新。

function najax() {
    $.ajax({
        url:"testjsp.jsp",
        type: "post",
        data: {
            crid: crid,
            sid: sid,
            ttid: ttid
        },
        async: false,
        cache: true,
        error: function(xhr, status, error) {
            alert("error" + error);
            alert("xhr" + xhr);
            alert("status" + status);
        },
        sync: true,
        success: function(responseText) {
            $("#disp_span").html(responseText);
        }
    });
}

Call to the code: 调用代码:

<input type="submit" name="Submit " id="submit"  value="Submit" class="btn"  onClick="najax();" ></input>

If I add a drop down menu then it works . 如果我添加一个下拉菜单,则可以使用。

<select name="select_menu1" onChange="najax();">
    <option value=" ">Select</option>
    <option value="cr_id">SUBMIT</option>
    <option value="sr_id">CANCEL</option>

If you want to make the ajax call with submit button ,then add the submit event to the form. 如果要使用“ submit按钮进行ajax调用,则将“提交”事件添加到表单中。

if you want to prevent the button from submitting the form and perform ajax operation ,then prevent the default action 如果要阻止button提交表单并执行ajax操作,则阻止默认操作

   $('#submit').click(function(e){
         e.preventDefault();
        ....//ajax call 
    });

To avoid submitting of the form change the input type to button 为避免提交表单,请将输入类型更改为button

<input type="button" name="Submit " id="submit" value="Submit" class="btn">

Then on button click call the function 然后在按钮上单击以调用该函数

$('#submit').click(function() {
    //najax()
        //Or call the ajax directly

    $.ajax({
        url: "testjsp.jsp",
        type: "post",
        data: {
            crid: crid,
            sid: sid,
            ttid: ttid
        },
        async: false,
        cache: true,
        error: function(xhr, status, error) {
            alert("error" + error);
            alert("xhr" + xhr);
            alert("status" + status);
        },
        sync: true,
        success: function(responseText) {
            $("#disp_span").html(responseText);
        }
    });
})

停止提交,如下所示

$("#formid").submit(function () { return false; });

甚至更好,只需使用type="button"按钮

You put the ajax request in a function, but you dont call it on the submit button like you do on the drop down menu onChange="najax();" 您将ajax请求放入函数中,但没有像在下拉菜单onChange="najax();"在提交按钮上调用它

<input onClick="najax();" type="submit" name="Submit " id="submit"  value="Submit" class="btn"></input>

this should work or use jquery to do that for you. 这应该工作或使用jquery为您做到这一点。 :) :)

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

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