javascript 将 AJAX POST 的参数传递给 Grails 控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13905416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing Parameters of AJAX POST to Grails Controller
提问by john Smith
I′m building a social network with Grails and got stucked on giving users inner their editprofile page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
我正在用 Grails 构建一个社交网络,并坚持让用户在他们的编辑配置文件页面内有机会将 youtube-Url 粘贴到文本字段中,然后通过单击一个按钮,JS 将 id 从粘贴的 URL 中正则表达式,一个 ajax 帖子是使用 youtube 视频的预览图像更新 div
the html looks like :
html 看起来像:
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
JS 看起来像:
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '');
var id = RegExp.;
jQuery.ajax({
type:'POST',
data:RegExp.,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
控制器看起来像:
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
和存储的视频看起来:
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
我只是不明白如何捕获 Ajax Post 的数据并使用其中包含 id 的预览图像更新 div,
can someone give a hint ? it is killing me
有人可以提示吗?它杀了我
采纳答案by micha
You should post the data like this:
你应该像这样发布数据:
jQuery.ajax({
type: 'POST',
data: { value: RegExp. },
...
After that you can access the posted data inside your grails controller with params.value
.
之后,您可以访问 grails 控制器中发布的数据params.value
。
回答by raffian
I got this working on Grails 2.0.4:
我在 Grails 2.0.4 上得到了这个:
Javascript/Ajax
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
在 Grails 中......
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON
parses the data and returns a ready to use object.
我喜欢这种方法,因为request.JSON
解析数据并返回一个随时可用的对象。