如何使用JSON或AJAX将表单字段值发送到REST服务 [英] How to send form field value to a REST service using JSON or AJAX

查看:104
本文介绍了如何使用JSON或AJAX将表单字段值发送到REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上有一个表单字段(电子邮件注册),电子邮件提供商希望我将其提交到他们的REST Web服务并获得响应.我从来没有用过JSON或AJAX这么费劲!

I have a form field (email signup) on the site, and the email provider wants me to submit it to their REST web service and get a response. I've never used JSON or AJAX before so floundering!

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响应的表单发布操作.现在会发生什么:

Currently, using Javascript and using window.location to visit the URL (which creates the action instead of posting it) they want it converted to a form post action with XML response. What happens now:

$(".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;
  }
});

推荐答案

我看到您正在使用jQuery,因此您可以使用$ .post这样将其发布到服务器:

I see you'r using jQuery so you can use the $.post to post to the server like this:

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);

$ .post的文档.
或者,您可以使用$ .post文档中提到的纯更长的Ajax版本.

我忘记了您无法将xhttpresuext扩展到使用JSONP所需的其他域,这是指向另一个

Documentation for $.post.
Or you can use the pure longer Ajax version it's mentioned in the documentation of the $.post.

I forget you can't do xhttpresuext to a different domain you need to use JSONP, here's a link to another SO post explaining everything by detail
Hope this help.

这篇关于如何使用JSON或AJAX将表单字段值发送到REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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