【问题标题】:Why is the data of an ajax request empty using angularjs?为什么使用angularjs的ajax请求的数据为空?
【发布时间】:2014-05-23 03:00:48
【问题描述】:

我正在测试 angularjs 的简单 ajax 请求,它似乎无法正常工作。发出请求,我得到 200,但数据没有通过。

$http({
        url: "myphp.php",
        method: "GET",
        dataType: "json",
        data: {"foo":"bar"}
    }).success(function(data, status, headers, config) {
        console.log(data);
    }).error(function(data, status, headers, config) {
        $scope.status = status;
});

<?php

echo var_dump($_GET);

?>

get 和 post 的结果相同。例如,如果我尝试访问 $_GET['foo'],则会遇到未定义的索引异常。

我做错了什么?

【问题讨论】:

  • PHP 的回报是什么?响应的正文是什么?
  • plnkr.co/edit/SEezJCY7ngBWy6W0IuJW 如果不满意,请解释一下,如果可以的话,如何使用php5.4 内置的http 服务器@CaioToOn 获取更多信息

标签: php json


【解决方案1】:

问题是您的数据以 JSON 编码的正文 ({dataType: "json", data: {"foo": "bar"}}) 发送到您的 PHP。不作为 GET/POST 参数。

当您在 body 中传递数据并且您的 PHP 试图在 $_GET 中检索时,您将收到 undefined index

不确定 PHP 中的正确方法是什么,但应该是这样的:

$requestBody = file_get_contents('php://input');
$requestBody = json_decode($requestBody);

【讨论】:

    【解决方案2】:

    由于 PHP 不接受 JSON 'application/json',因此您需要从 angular 适当地更新您的标头和参数。

    首先,参数化你的数据:

    data: $.param({ "foo": $scope.fooValue })
    

    然后,将以下内容添加到您的$http

     headers: {
         'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
     }, 
    

    如果您的所有请求都发往 PHP,则可以在配置中全局设置参数,如下所示:

    myApp.config(function($httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2018-08-29
      • 2019-10-06
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      相关资源
      最近更新 更多