2013-03-18 51 views
0

我在該網站上有一個表單字段(電子郵件註冊),並且電子郵件提供商希望我將其提交到其REST Web服務並獲得響應。我從來沒有用過JSON或AJAX之前這麼掙扎!如何使用JSON或AJAX將表單字段值發送到REST服務

的HTML:

<form> 
    <input type="hidden" name="gid" value="12345678"> 
    <input type="hidden" name="user.CustomAttribute.NewsletterPopUp" value="Global"> 
    <input type="hidden" name="user.CustomAttribute.NewsletterOptIn" value="True">" value="True"> 
    <input type="text" name="uemail" class="email_input_field" value="please enter your email" size="30" maxlength="64" onFocus="clearText(this)"> 
    <input type="submit" name="signup" value="signup" class="email_submit_button"> 
</form> 

目前,使用JavaScript和使用window.location的訪問URL(產生作用,而不是張貼的),他們希望它轉換爲表格後行動XML響應。現在會發生什麼:

$(".email_submit_button").click(function(){ 
    var uemail = $('.email_input_field').val(); 
    window.location = "http://example.com/automated/action.jsp?action=register&errorPage=/automated/action.jsp&gid=12345678&uemail="+uemail+"&user.CustomAttribute.NewsletterPopUp=Global&user.CustomAttribute.NewsletterOptIn=True"; 
    return false; 
    } 
}); 

回答

1

我找你使用jQuery,所以你可以使用$。員額張貼到這樣的服務器,請參閱:

var url = "http://example.com/automated/action.jsp" 
var data ={ 
    "gid": form.gid, 
    "action": register, 
    "uemail": form.uemail, 
    "errorPage": "/automated/action.jsp", 
    "user.CustomAttribute.NewsletterOptIn": user.CustomAttribute.NewsletterOptIn, 
    "user.CustomAttribute.NewsletterPopUp": user.CustomAttribute.NewsletterPopUp 
}; 
var success_func = function(data){ 
    //do what you want with the returned data 
}; 
$.post(url, data, success_func); 

Documentation for $.post
或者您可以使用$ .post文檔中提到的純Ajax更長的版本。
編輯:
我忘了,你不能做對xhttpresuext您需要使用JSONP不同的域,這裏的另一個SO post explaining everything by detail
希望這有助於鏈接。

0
$(".email_submit_button").submit(function(e) { 
       // stop form from submitting 
       e.preventDefault(); 
       // Grab all values 
       var uemail = $('.email_input_field').val(); 
       // make a POST ajax call 
       $.ajax({ 
        type: "POST", 
        url: "YOUR URL", // set your URL here 
        data: { 
        uemail: uemail // send along this data (can add more data separated by comma) 
       }, 
       beforeSend: function (xhr) { 
       // maybe tell the user that the request is being processed 
        $("#status").show().html("<img src='images/preloader.gif' width='32' height='32' alt='processing...'>"); 
       } 
       }).done(function(response) { 
        // do something with the received data/response 
        //$("#status").html(response); 
       }); 
      }); 

不知道「.email_submit_button」是給提交按鈕或窗體類..你需要使用給予形式的ID或類,而不是提交按鈕..希望這有助於

+0

謝謝,我收到以下錯誤消息:XMLHttpRequest無法加載http://example.com/automated/action.jsp。 Access-Control-Allow-Origin不允許Origin http://differentserver.com。有任何想法嗎? – JayDee 2013-03-18 16:40:17

+0

檢查了這一點http://stackoverflow.com/questions/8153832/xmlhttprequest-changes-post-to-option – 2013-03-18 16:43:19

相關問題