[英]How to pass parameters to an action by a post or ajax call in jQuery?
My intent is to pass a couple of parameters to an action in struts2, but I want that these parameters have to be hidden, so the GET call is not recommended. 我的意图是将几个参数传递给struts2中的一个动作,但是我希望这些参数必须隐藏,因此不建议使用GET调用。 I thought that a post or ajax call in jQuery could be a good idea to do so, but the parameters are null and the redirect to the jsp page doesn't work. 我以为jQuery中的post或ajax调用可能是个好主意,但是参数为null,并且重定向到jsp页面不起作用。 Here are the Action and the javascript codes: 这是操作和javascript代码:
MyAction.java 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 file.js
function myFunction(){
var pkId = "pkId1";
var url = "./myAction.action";
var type = "type1";
$.ajax(url, {pkId : pkId, type : type});
}
Updated code: 更新的代码:
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.
});
}
What you have done is right. 您所做的是正确的。 Instead of the $.ajax()
, use the $.post
shortform: 代替$.ajax()
,使用$.post
缩写:
$.post(url, {pkId : pkId, type : type}, function (resp) {
// resp is the response from the server after the post request.
});
So the file.js
contains: 所以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.
});
}
If you don't want an Asynchronous request, make it a default form. 如果您不希望使用异步请求,请将其设置为默认表单。
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();
}
Hope this helps! 希望这可以帮助!
$.ajax({
url: "<your url>",
type: "POST",
data: JSON.stringify(<your data>)
}).done(function(response) {
//TODO response from the sever
});
Since the default request method of $.ajax
is GET, you should specify the type parameter as 'POST' to do a post
request. 由于$.ajax
的默认请求方法是GET,因此您应该将type参数指定为'POST'来进行post
请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.