javascript - 如何获取 html 和 php 之间的 json 值?

标签 javascript php jquery ajax json

我正在制作可以投票赞成和反对的函数。基本上,当我尝试在其中实现 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/

相关文章:

php - MySqli : num_rows of grouped by hour()

javascript - 将鼠标坐标转换为HTML5 Canvas转换后上下文的最佳方法

javascript - AJAX 未检测到错误

Android 的 PHP 套接字

jquery - Ajax.ActionLink 与 Html.ActionLink + Jquery.Ajax 调用

javascript - 正确输入的文字会改变图像吗?

javascript - 单击 window.open 时如何加载 JavaScript 函数?

javascript - 如何通过 Facebook Graph Api 获取用户的 friend 在生日当天在用户墙上发布的帖子?

javascript - Protractor :如何获取从命令行传递的 baseUrl?

php - 使用连接在 HTML 标记内回显带有条件的 PHP 函数