簡體   English   中英

如何通過jQuery中的post或ajax調用將參數傳遞給操作?

[英]How to pass parameters to an action by a post or ajax call in jQuery?

我的意圖是將幾個參數傳遞給struts2中的一個動作,但是我希望這些參數必須隱藏,因此不建議使用GET調用。 我以為jQuery中的post或ajax調用可能是個好主意,但是參數為null,並且重定向到jsp頁面不起作用。 這是操作和javascript代碼:

MyAction.java

public class MyAction extends ActionSupport{

     private Long pkId;
     private String type;

     public String execute() {
        String pkId = getPkId();
        String type = getType();
        return Action.SUCCESS;
     }
}

file.js

function myFunction(){
    var pkId = "pkId1";
    var url = "./myAction.action";
    var type = "type1";
    $.ajax(url, {pkId : pkId, type : type});
}

更新的代碼:

function myFunction(){
        var pkId = "pkId1";
        var url = "./myAction.action";
        var type = "type1";
        $.post(url, {pkId : pkId, type : type}, function(resp){
             // resp is the response from the server after the post request.
        });
    }

您所做的是正確的。 代替$.ajax() ,使用$.post縮寫:

$.post(url, {pkId : pkId, type : type}, function (resp) {
  // resp is the response from the server after the post request.
});

所以file.js包含:

function myFunction() {
    var pkId = "pkId1";
    var url = "./myAction.action";
    var type = "type1";
    $.post(url, {pkId : pkId, type : type}, function (resp) {
      // resp is the response from the server after the post request.
    });
}

如果您不希望使用異步請求,請將其設置為默認表單。

function myFunction() {
    var pkId = "pkId1";
    var url = "./myAction.action";
    var type = "type1";
    var FormD = '<form method="post" action="' + url + '" id="frmFakeSubmit">';
    FormD += '<input type="hidden" name="pkId" value="' + pkId + '" />';
    FormD += '<input type="hidden" name="type" value="' + type + '" />';
    FormD += '</form>';
    $("body").append(FormD);
    $("#frmFakeSubmit").submit();
}

希望這可以幫助!

 $.ajax({
     url: "<your url>",
     type: "POST",
     data: JSON.stringify(<your data>)
 }).done(function(response) {
    //TODO response from the sever
 });

由於$.ajax的默認請求方法是GET,因此您應該將type參數指定為'POST'來進行post請求。

暫無
暫無

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

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