doujuanju3076 2017-12-26 12:51 采纳率: 0%
浏览 82
已采纳

如何通过javaScript / jquery从php获取json返回值?

This is my javaScript code :

$(document).ready(function() {
    $('#IMDB').click(function() {  
       var MovieID = $('#MovieID').val();

       $.post('action/action.php', { url: "http://api.themoviedb.org/3/movie/"+MovieID
+"?append_to_response=credits,images&api_key=myapikey" }, function(data) {
           var aliases = data.aliases;  
           document.getElementById('GamesTitle').value = aliases;
       });
    });
});

and this my php code

header('Content-Type: application/json');
    $url = $_POST['url'];
    $context = stream_context_create(['http' => ['user_agent' => 'API Test UA']]);
    $response = file_get_contents($url, false, $context);
    $json = json_decode($response, true);
    foreach($json as $item){
        if($item['aliases'] !== null && $item['aliases'] !== 'O' && $item['aliases'] !== '1'){
            $aliases .= $item['aliases'];  // its give the result fine in php page
        }   
    }

    echo json_encode(array(
      'aliases' => $aliases
    ));
    return true;

but when i click my button to get all information its not getting anything. and i dont get any error in console or anywhere so i can't find my problem.

and when i return value in php page it returns like this - >

O null null null null {my result} 1

thats why i have to skip this O and 1 with

if($item['aliases'] !== null && $item['aliases'] !== 'O' && $item['aliases'] !== '1') {// .... now its ok } 

if you remove this from php it will work fine. like this

header('Content-Type: application/json');
    $url = $_POST['url'];

    echo json_encode(array(
      'aliases' => 'test' /// now its work fine
    ));
    return true;
  • 写回答

1条回答 默认 最新

  • duannei1477 2017-12-26 13:23
    关注

    add ."json"... like:

    $(document).ready(function() {
    $('#IMDB').click(function() {  
       var MovieID = $('#MovieID').val();
    
       $.post('action/action.php', { url: "http://api.themoviedb.org/3/movie/"+MovieID+"?append_to_response=credits,images&api_key=myapikey" }, function(data) {
           var aliases = data.aliases;  
           document.getElementById('GamesTitle').value = aliases;
       }, "json");
    });
    });
    

    now the return data will be interpreted as JSON.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试