jQuery json函数返回null [英] jquery json function returning null

查看:104
本文介绍了jQuery json函数返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的jquery脚本:

I have a jquery script as below:

$.ajax({
   type: "GET",
   url: "http://www.site.com/v4/ajax/get_song_info.php",
   data: ({id : song_id }),
   dataType: "json",
   success: function(data)
   {
      alert( "Data: " + data );
   }
 });

以及相关的php页面:

And the associated php page:

<?php

    include_once '../connect.php';

    $song_id = $_GET['id'];

    $query = mysql_query("SELECT * FROM songs WHERE id = '$song_id' LIMIT 1");

    $song = mysql_fetch_row($query);

    $song_info = array( htmlentities($song[3]) , htmlentities($song[4]) );

    header('Content-Type: application/json');
    echo json_encode($song_info); 
?>

当我在浏览器中单独调用php时,它会返回如下内容:["Peaches","I Feel Cream (Proxy Remix)"]

The php returns something like this when I call it on its own in a browser: ["Peaches","I Feel Cream (Proxy Remix)"]

但是,当我进行jQuery调用时,我的警报显示为数据:空"

However when I make the jQuery call my alert shows 'Data: null'

推荐答案

我注意到您使用的是绝对URL,而不是相对URL.如果您的网页也没有通过http://www.site.com进行投放,则说明您遇到了相同来源政策" . SOP是由浏览器实现的安全机制.

I notice that you've used an absolute URL rather than a relative one. If your page isn't also being served from http://www.site.com, you're running into the Same Origin Policy. The SOP is a security mechanism implemented by browsers.

您可以通过多种方法来解决此问题.如果您控制服务器并且不需要支持IE6或IE7,则可以实现

You have a couple of options for working around this. If you're in control of the server and you don't need to support IE6 or IE7, you can implement Cross-Origin Resource Sharing. In most modern browsers, if the server is CORS-enabled, your ajax calls will just start working (the browser handles it under-the-covers). IE6 and IE7 don't have any support for CORS, though, and IE8's requires that the client-side code do something special.

另一个选项是 JSONP ,它利用了尽管您可以不要进行跨域的Ajax调用(除非您有CORS),页面从远程主机加载脚本是完全可以的.因此,您将加载脚本,其中包括数据,并且会回叫您以使您知道其中的内容. JSONP的优势在于,它现在可以与所有主要的浏览器一起使用. jQuery在 ajax 调用中内置了JSONP支持.

Another option is JSONP, which makes use of the fact that although you can't do a cross-origin ajax call (unless you have CORS), it's perfectly okay for a page to load a script from a remote host. So you load the script, which includes the data and which calls you back to let you know it's there. The advantage of JSONP is that it works with all major browsers, right now. And jQuery has JSONP support built into its ajax call.

这篇关于jQuery json函数返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆