Ajax表单发送

时间:2011-07-22 13:54:19

标签: jquery html ajax json forms

好吧,由于AJAX绝对是一个薄弱的领域,我已经超越了我的头脑。我有一个页面,需要通过ajax将注册表单发送到另一个域进行处理,然后返回成功/失败消息。

使用以下代码时,页面只会刷新并且不会发送任何内容吗?

表格代码:

<form method="post" onSubmit="return submitGetApp();" class="kinkast_signup"> 
  <input id="login_email" type="text" name="to" />
  <input id="signInButtonSubmit" type="submit" name="action" value="Send" />
</form>

jQuery代码: $('#signInButtonSubmit')。点击(function(e){

    //Get the data from all the fields
    var number = $('input[name=to]');

    //Simple validation to make sure user entered something
    //If error found, add hightlight class to the text field
    if (number.val()=='') {
        name.addClass('hightlight');
        return false;
    } else name.removeClass('hightlight');

    //organize the data properly
    var data = 'number=' + number.val();

    //show the loading sign
    $('p.ajax_message').hide();

    //start the ajax
    $.ajax({
        //this is the php file that processes the data and send mail
        url: "http://video.kinkast.com/getapp", 

        //GET method is used
        type: "POST",

        //pass the data         
        data: data,     

        //Do not cache the page
        cache: false,

        //success
        success: function () {              
            $('p.ajax_message').html('Success!');
            alert('Worked!');                    

            },

        //Failure
        error: function(xhr, status, e) {
            alert(status, e);
        } 

    });

    //cancel the submit button default behaviours
    return false;
}); 

有人可以查看代码,看看我错过了什么吗?另外,要查看它,请访问this link

2 个答案:

答案 0 :(得分:0)

您无法将ajax帖子发送到其他域名。

这有助于防止诸如跨站点脚本攻击(XSS攻击)之类的事情。

有一些框架可以让你做ACD这样的事情,但在大多数情况下我不会推荐这种做法。

<强>更新

以下是您的代码的有效版本:http://jsfiddle.net/4tMN3/

你会注意到一些新事物。

首先,我使用propper jQuery事件机制附加事件。

$('#mySubmitForm').submit(function(event){})

这比以实际形式硬编码事件要好得多。

其次你会注意到使用:

event.preventDefault();

这是用于防止表单默认行为(即提交)而不是返回false的propper jQuery方法。

答案 1 :(得分:0)

有很多方法可以使用插件通过jquery创建跨域json请求。它使用YQL将页面转储作为json请求返回。它不是真的推荐,但如果你真的需要你可以。这是一个链接,这里有一个链接到他的github最新版本。我最近使用它进行了一些测试,而且一切都运行得很好,我马上得到一个JSFiddle。

http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

还有一个页面通过YQL发布: http://www.wait-till-i.com/2009/11/16/using-yql-to-read-html-from-a-document-that-requires-post-data/

示例JSFiddle: http://jsfiddle.net/M6X6n/1/