【问题标题】:How can I use json on localhost (MAMP)?如何在 localhost (MAMP) 上使用 json?
【发布时间】:2017-09-16 23:21:11
【问题描述】:

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");
        }
    })
});

更新.php

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

我想在 localhost 上使用 json。但它不起作用。 我正在使用 MAMP。

【问题讨论】:

  • @Jarla 遇到什么错误?
  • 你不需要使用 header('Content-type: application/json');在 update.php 和 ajax 中,你需要在使用数据值之前使用 JSON.parse(data)
  • 您遇到了哪些错误/异常?
  • @vSugumar 您确实需要 application/json 内容类型,因为该应用程序提供 json。删除它没有意义
  • 我认为它被否决了,因为问题不包含错误;)。没有明确的例外,很难提供帮助。

标签: php json ajax localhost mamp


【解决方案1】:

在 ajax 调用中使用 DataType : 'json' 并将 encode 设置为 true。我已经做了一个工作小提琴给你看,它正在工作。

  $(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);
            }
        })
 });
<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>

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: *'); 你实际上并不需要这个我这样做是为了让 fiddle 能够从我的服务器访问更新文件,所以你可以实时看到这个。

结果:

【讨论】:

  • 它在我的页面上不起作用。也许是因为我在本地主机上?
  • 我也在 localhost 上这样做了.. 检查控制台它应该打印一些东西
  • 控制台不打印任何东西
  • 这很奇怪,你能运行上面的代码sn-p吗,你会看到它的工作方式如你所愿
  • 是的,我知道,那是倒霉
猜你喜欢
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2015-05-15
  • 2013-01-18
  • 2013-01-09
  • 1970-01-01
  • 2021-03-21
相关资源
最近更新 更多