繁体   English   中英

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

[英]How to get json return value from php by javaScript / jquery?

这是我的 javaScript 代码:

$(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;
       });
    });
});

这是我的 php 代码

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;

但是当我点击我的按钮获取所有信息时,它没有得到任何信息。 我在控制台或任何地方都没有收到任何错误,所以我找不到我的问题。

当我在 php 页面中返回值时,它会像这样返回 - >

O null null null null {我的结果} 1

这就是为什么我必须跳过这个 O 和 1

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

如果您从 php 中删除它,它将正常工作。 像这样

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

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

添加."json" ... 像:

$(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");
});
});

现在返回data将被解释为 JSON。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM