我的代码看起来像这样。
<a href="#" class="5" id="link">Next</a>
<scipt>
$('#link').click(function(){
var val = $(this).attr('class');
$.post('nextpage.php', { class:val }, function(){
window.location.href = "nextpage.php";
return false;
});
});
</scipt>
这是我的尝试。我在$ .post()中使用和不使用函数()尝试了上面的jQuery代码。使用功能,它只是重定向页面而不发布变量。没有这个功能,它没有做任何事情。
我的代码中有几个链接各自的类。我没有将它的类用于任何样式。我只想将anchor
标记的class属性的值与id=link
一起发送到下一页。我希望通过POST方法而不是GET方法来实现。我想通过jQuery或JavaScript来实现。
答案 0 :(得分:4)
如果没有表格,你不能这样做,你只需这样做:
<form name="formName" id="formName" action="nextpage.php" method="POST">
<a href="#" class="5" id="link">Next</a>
<input type="hidden" value="" name="class" id="class"/>
</form>
<scipt>
$('#link').click(function(){
var val = $(this).attr('class');
$("#class").val(val);
document.getElementById("formName").submit();
});
</scipt>
答案 1 :(得分:0)
问题是post()是一个AJAX的东西,因此它确实发布但保持在同一侧。之后,你的window.location是一个新请求,并且当时没有发送变量。
在这种情况下,我会使用submit()并在HTML中使用隐藏输入的表单,该表单将带有&#34;携带&#34;变量:http://api.jquery.com/submit/
答案 2 :(得分:0)
在$ .post()中发送json对象
var val = '{ "class" : "' +$(this).attr('class')+ '"}';
var obj = JSON.parse(val);
$.post('nextpage.php', obj, function(){
修改强>
你想要什么是无法实现的,因为ajax无法重定向..如果你使用窗口位置重定向那么它就不会有ajax发送的POST数据..
答案 3 :(得分:0)
。首先,由于 anchor 标记上的默认点击事件,您需要阻止直接重定向
<scipt>
$('a #link').click(function(e){
e.preventDefault();
var val = $(this).attr('class');
$.post('nextpage.php', { class:val }, function(){
window.location.href = "nextpage.php";
return false;
});
});
</scipt>
答案 4 :(得分:0)
好的,首先,我希望这不是直接从您的代码中复制粘贴的。如果是这样,你有几个拼写错误
<scipt> <-- Typo
$('#link').click(function(){
var val = $(this).attr('class');
$.post('nextpage.php', { class:val }, function(){
window.location.href = "nextpage.php";
return false;
});
});
</scipt> <-- Typo
接下来,这是一个AJAX请求,这意味着除非你有某种回调(来自服务器的反馈),所有这些似乎都会默默地发生。
尝试类似的事情(直接从.post()获取):
// Send the data using post
var posting = $.post( 'nextpage.php' , { class: val } );
// Put the results in a div
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
<a href="#" class="5" id="link">Next</a>
<div id="result"></div>