ajax不能json_decode一个GET字符串

时间:2016-02-08 23:19:34

标签: javascript php angularjs ajax

我正在使用angularjs从表单获取userId,userTitle和userComment。 从那个控制器我发送到PHP页面。该页面应与服务器通信。 当我尝试发送整数时,一切都很好,但是当我尝试发送字符串时,我无法得到回声。 这是我在控制器中的功能:

$scope.addComment = function(userId, userTitle, userComment) {
           $.ajax({                           
              url: 'http://localhost/blip/app/phpCore/sendReview.php',//the script to call to get data          
              data: { 
              userId:userId,
              userTitle:userTitle,
              userComment:userComment
              },//you can insert url argumnets here to pass to review.php
              type: 'get', //for example "get"
              dataType: 'json'})//data format   
              .done(function( msg ) { //on recieve of reply
              alert( "Data Saved: " + msg );
          });  // end ajax   
         }; //end angular scope  

这是我的PHP:

<?php
include('blip_4815162342_108.php');
$UserID = $_GET['userId'];
echo $UserID;
?>

当我发送整数为“userId:userId”echo $ UserID;正在工作并返回.done警告“数据已保存:”+ 123。 php中的代码更复杂,但我在这一点上存货。

2 个答案:

答案 0 :(得分:1)

在您的AJAX请求中,您指定服务器将返回JSON。

来自jQuery docs

  

dataType(默认值:Intelligent Guess(xml,json,script或html))

     

类型:字符串您期望从中返回的数据类型   服务器

由于服务器返回一个字符串echo $UserID; Ajax函数实际上会转到它没有定义的错误函数。如果您添加.error(function(e){console.log(e);});,则会看到userId。

所以只需让你的服务器通过json_encoding你的返回值返回JSON:

<?php
include('blip_4815162342_108.php');
$UserID = $_GET['userId'];
echo json_encode(['userID':$UserID]);
?>

或者更改您的AJAX调用以接受非JSON。只需删除dataType声明。

答案 1 :(得分:1)

在角度你可能想要使用$ http ...

它的用法是这样的:

$scope.addComment = function(userId, userTitle, userComment) {
    var data = JSON.stringify({ 
          userId:userId,
          userTitle:userTitle,
          userComment:userComment
          });

    var req = {
       method: 'POST',
          url: 'http://example.com',
       headers: {
          'Content-Type': undefined
       },
          data: data
       }

    $http(req).then(function successCallback(response) {

        JSON.parse(response)

        // this callback will be called asynchronously
        // when the response is available
     }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
     });  
}; //end of scope

请记住,您需要在控制器中注入$ http。我已将此编辑为帖子,因为它似乎更多是您正在寻找的功能。在这种情况下,您需要更改您的php以从POST而不是GET获取数据。

相关问题