如何在localhost(MAMP)上使用json?

时间:2017-04-20 10:57:06

标签: php json ajax localhost mamp

index.php

    <button class="button">color</button>
    <div class="blue"></div>
    <div class="red"></div>

的script.js

$(".button").click(function(){
  $.ajax({
        url: "update.php",
        type: "POST",
        success: function (data) {
            $(".blue").html(data.blue);
            $(".red").html(data.red);
              alert("success");
        }
    })
});

update.php

$array['blue'] = "blue content";
$array['red'] = "red content";
header('Content-type: application/json');
echo json_encode($array);

我想在localhost上使用json。但它没有用。 我正在使用MAMP。

1 个答案:

答案 0 :(得分:1)

在ajax调用上使用DataType : 'json'并将encode设置为true。我做了一个工作小提琴让你看,这是有效的。

&#13;
&#13;
  $(document).on("click", ".send", function (event) {
   $.ajax({
            url: "http://www.personaldev.co.za/json/update.php",
            type: "POST",
            dataType : 'json',
            encode : true,
            success: function (data) {
                console.log(data);
                $(".blue").html(data.blue);
                $(".red").html(data.red);
            }
        })
 });
&#13;
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
 

<button class="send">Send</button>
<div class="blue" style="background: blue;color: white"></div>
<div class="red" style="background: red;color:white"></div>
&#13;
&#13;
&#13;

<强> update.php

<?php
    header('Access-Control-Allow-Origin: *');
    $array['blue'] = "blue content";
    $array['red'] = "red content";

    echo json_encode($array);
?>

Nb:header('Access-Control-Allow-Origin: *');您实际上并不需要这样做我这样做,以便小提琴能够从我的服务器访问更新文件,因此您可以在现场直播中看到这一点。

结果:

enter image description here