简单的jsonp不能与PHP服务器一起使用 [英] simple jsonp not working with php server

查看:106
本文介绍了简单的jsonp不能与PHP服务器一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试按照一些基本示例进行操作,但它不起作用.我不确定我是否完全理解jsonp,但是我遵循了基本教程,并且在直观的水平上,我看不到任何错误. (当然,我缺少一些东西,因此是个问题).

I tried following some basic examples, and it is not working. I am not sure I completely understand jsonp, but I followed the basic tutorials and on an intuitive level, I can't see anything wrong. (Of course, I am missing something, hence the question).

JavaScript代码:

JavaScript code:

postData = $(this).serialize();

console.log(postData);

$.ajax({

    data: postData,
    url: 'externaldomain.php',
    dataType: 'jsonp',

    success: function(data){
        console.log(data);
        alert('Your comment was successfully added');
    },
    error: function(){
        console.log(data);
        alert('There was an error adding your comment');
    }
});

PHP代码:

$tag = mysql_real_escape_string($_GET["callback"]);

令人讨厌的部分是它甚至没有向我显示Google的错误.

The annoying part is that it is not even showing me an error to Google for.

有人可以帮忙解决这个问题吗?

Can anyone help out figuring the problem please?

推荐答案

由于您尚未发布完整或相关的PHP代码,因此我假设它看起来像这样

Since you haven't posted your full or relevant PHP code I'm going to assume it looks like this

$tag = mysql_real_escape_string($_GET["callback"]);
echo $tag."(";
// print json here
echo ")"

我不太确定jquery如何处理jsonp请求,但我以前所做的是向DOM中添加一个看起来像这样的新脚本标签

I'm not really sure how jquery handles jsonp requests but what I used to do is add a new script tag to the DOM that looks like this

<script> function cb(json) { alert(json); } </script> // (I)
<script src="{url}?callback=cb"></script> // (II)

在加载(II)时,由于我们有一个回调,所以我们要包含在DOM中的脚本如下所示:

When (II) is loaded, and because we have a callback then the script that we are including in the DOM looks like this

cb({
   // json goes here
})

几乎就像对我们正在使用的名为cb的某个函数的函数调用.因此,自然有cb的实现(在(I)中).该实现类似于jQuery的ajax中的success(data)函数.它用于使用和操作所请求的json

which pretty much is like a function call to some function called cb that we are using. It is therefore natural to have an implementation of cb (which is in (I)). That implementation is similar to the success(data) function in jQuery's ajax. It is used to use and manipulate the json requested

但是我注意到您正在使用jsonp在ajax调用中执行POST请求.不幸的是(根据此问题如何进行发出一个用jQuery指定contentType的jsonp POST请求?)由于实现目的,用JSONP进行POST是不可行的.

However I noticed that you are doing a POST request along the ajax call with jsonp. Unfortuantely (according to this question How to make a jsonp POST request that specifies contentType with jQuery?) doing POST with JSONP is not feasable due to implementation pursposes.

这篇关于简单的jsonp不能与PHP服务器一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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