我正在制作可以投票赞成和反对的函数。基本上,当我尝试在其中实现 jquery ajax 时,它没有提供正确的值。
我的文件类似于,
<?php
//some data navigation menu and other things here
//my function is here
if($_POST['rate']=='down') {
$rate=get_post_meta($post->ID,'down',true);
$rate=$rate+1;
update_post_meta($post->ID,'down',$rate);
setcookie(rate, 1, time() + (86400 * 30), "/"); // 86400 = 1 day
$totaldn=get_post_meta($post->ID,'down',true);
}
现在我希望 $totaldn 在 ajax 中返回,但它返回的是旧值,所以我实现了 header 类型系统并将其声明为 json,
if(isset($_POST['rate'])) {
header('Content-Type: application/json');
$myData = array();
$myData['abc']="Hello World";
echo json_encode($myData);
现在它开始给我错误,这种意外的语法只有当我将此代码放在文件顶部时才起作用,否则我的 jquery ajax 代码要么返回完整的 html 页面。
我的问题是如何将此 header 类型放在 html 和 php 中间而不出现错误
我的 jquery ajax 代码是。
$(document).ready(function() {
$("#bmup").click(function(){
$.ajax({
url: window.location,
type: "POST",
data: "rate="+$("#bvdn").val(),
datatype: 'json',
success: function(mydata){
$.each( mydata, function( key, val ) {
alert( val);
});
//alert($.getJSON(mydata));
$("#bmup").html(mydata);
},
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
});
});
最佳答案
为什么你不尝试这样的事情呢?
$totaldn=$rate;
并在 html 元素中设置totaldn... 您应该测试 update_post_meta。如果是真的,那你就可以认为没问题了。
查看 WordPress 文档:Link
Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure. NOTE: If the meta_value passed to this function is the same as the value that is already in the database, this function returns false.
关于javascript - 如何获取 html 和 php 之间的 json 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743465/