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

如何通过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 vmtools环境不正常
  • ¥15 请问如何在Ubuntu系统中安装使用microsoft R open?
  • ¥15 jupyter notebook
  • ¥30 informer时间序列预测
  • ¥20 SSR引物多态性分析
  • ¥15 大漠插件在Win11易语言注册调用和免注册灵异事件,VS上注册调用完全没问题
  • ¥15 Addressable缓存机制做热更新的问题
  • ¥15 微信开发者工具vant组件
  • ¥15 iPhone iCloud云盘资料删除,MAC丢失50多G桌面资料
  • ¥20 希望各位学长可以给我答疑