[英]How to post data with AJAX and jQuery?
I have HTML like this: 我有这样的HTML:
<script src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<p>1</p> <!-- this is loaded with <?php echo $item->id; ?> -->
<a id='delBtn1' my-data='tnt' onlick='del(this)' href='index.php?page=mypage'>
<img src='del.ico'/>
</a>
<script>
$(document).ready(function(){
function del(e) {
var p = $('a< p' ).html();
$.post('index.php?page=mypage', {
msg: e.getAttribute('my-data'),
id: p
}, function(data, status) {
alert("Sent " + data.msg + ' : '+ status);
});
}
});
</script>
I don't know why I can't get the the id
'1' and post to index with a '?' 我不知道为什么我不能获得
id
'并用'? in the URL for data {msg, id}. 在数据{msg,id}的URL中。
i want to get ID in
<p>
and my-data in<a>
then sent to index.php?page=mypage我想在
<p>
获取ID,在<a>
获取my-data,然后发送至index.php?page = mypage
Firstly what you're calling the id
is just the innerText of the p
element. 首先,您所谓的
id
只是p
元素的innerText。 To retrieve that you need to traverse the DOM from the provided a
element using prev()
and retrieve it. 要检索您需要使用
prev()
从提供a
元素中遍历DOM并进行检索。
Also note that my-data
is not a valid attribute for an a
element. 另外请注意,
my-data
是不是一个有效的属性a
元素。 To store custom data with an element you should use data-*
attributes. 要使用元素存储自定义数据,应使用
data-*
属性。 You should also use unobtrusive Javascript to attach your events instead of clunky and outdated on*
event attributes. 您还应该使用简洁的Javascript附加事件,而不是笨拙且过时的
on*
事件属性。
With that said, the following should work for you: 话虽如此,以下应该为您工作:
<p>1</p>
<a id="delBtn1" class="delBtn" data-my-data="tnt" href="index.php?page=mypage">
<img src="del.ico" />
</a>
$(document).ready(function(){
$('.delBtn').click(function(e) {
e.preventDefault(); // stop the normal link behaviour
var $el = $(this);
$.post($el.attr('href'), {
msg: $el.data('my-data'),
id: $el.prev('p').text(),
}, function(data, status) {
alert("Sent " + data.msg + ' : '+ status);
});
});
});
Finally you state that you want the request data to be put in the URL, if that's the case you should use $.get
instead of $.post
. 最后,您声明您希望将请求数据放入URL中,如果是这种情况,则应使用
$.get
而不是$.post
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.