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 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)