使用jquery ajax将数据发送到远程服务器 [英] send data to remote server with jquery ajax

查看:197
本文介绍了使用jquery ajax将数据发送到远程服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,它会生成一个javascript代码,在网站上显示一个小部件。当通过窗体小部件表单提交数据时,它会使用jQuery ajax函数将数据发布到服务器。

I'm working on an app, that generates a javascript code, which displays a widget on a website. When a data is submitted through the widget form, it posts the data to the server with a jQuery ajax function.

问题是我正在使用成功回调如果我将小部件放在不同主机上的网站上,将永远不会被解雇。我知道这是因为javascript阻止了跨域ajax并且我应该使用jsonp,但是我想知道为什么成功事件没有被触发,如果数据被正常发送到服务器?

The problem is that I'm using a success callback that will never be fired if I place the widget on a website, which is on a different host. I know that its because javascript prevents cross-domain ajax and that I should use jsonp, but I'm wondering why success event isn't triggered, if the data is sent to the server normally?

以下是代码:

$.ajax({
  type: 'POST',
  url: report_url,
  data: $(form).serialize(),
  success: function() {
    alert("success called!");
  }
});

用jsonp执行相同操作的最佳方法是什么?我有点困惑,如果我应该用jsonp和如何,因为它需要定义一个jsonp回调参数。

What would be the best way to do the same thing with jsonp? I'm a little confused if I should do it with jsonp and how, since it requires to define a jsonp callback parameter.

感谢您的帮助

推荐答案

嗯,你可以尝试使用 JSONP

现场演示: http://jsfiddle.net/5CUk2/

(请检查浏览器控制台)

$(function() {

    //Example using flickr API
    var diffDomainUrl = 'http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=mycallback&tags=monkey&tagmode=any&format=json';

    $('#jsonpbtn').on('click', function() {
        $.ajax({
            url: diffDomainUrl,
            dataType: 'jsonp',
            data: {},
            success: function (data, textStatus) {
                console.log(textStatus);
                console.log(data);
            },
            jsonpCallback: 'mycallback'
        });
    });

});






顺便说一下,你可以尝试其他可能的通过查看这个来制作跨域请求的方式,也许可以提供帮助:


By the way, you can try other possible "ways" to make a cross-domain request by taking a look to this, maybe can help:

http://usejquery.com/blog/jquery-cross-domain-ajax-guide

这篇关于使用jquery ajax将数据发送到远程服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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