使用 jquery ajax 传递数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19438937/
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 data with jquery ajax
提问by Tyler Durden
I always get the 'error' alert, and I can't figure out what's wrong. I'm just trying to get back the string ("testexpression") that I send. It has to be something with the data part, because without a parameter it works.
我总是收到“错误”警报,我无法弄清楚出了什么问题。我只是想取回我发送的字符串(“testexpression”)。它必须与数据部分有关,因为没有参数它就可以工作。
Here's the jquery part:
这是jquery部分:
<script>
$("#meaning").blur(function () {
$.ajax({
type: "POST",
url: '/GetMeaning/',
data: {"expression" : "testexpression"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$("#dictionaryDropDown").html(data);
}
function errorFunc() {
alert('error');
}
})
</script>
And this is the controller:
这是控制器:
public class GetMeaningController : Controller
{
//
// GET: /GetMeaning/
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string expression)
{
return Json(expression, JsonRequestBehavior.AllowGet);
}
}
(update: the type is post, I was just trying it out with get as well, and I left it in)
(更新:类型是 post,我也只是用 get 尝试了一下,我把它留在了)
回答by Dennis Flagg
You need to send data as a string/json. You are sending a javascript object. Also, The URL might need to be a absolute url and not a relative url
您需要将数据作为字符串/json 发送。您正在发送一个 javascript 对象。此外,该 URL 可能需要是绝对 url 而不是相对 url
$("#meaning").blur(function () {
$.ajax({
type: "POST",
url: '/GetMeaning/',
data: JSON.stringify({expression: "testexpression"}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$("#dictionaryDropDown").html(data);
}
function errorFunc() {
alert('error');
}
})
回答by beautifulcoder
On the back end side I recommend
在后端,我推荐
return Json(
new { this.expression = expression },
JsonRequestBehavior.AllowGet);
Assuming you want to send back an actual JSON and not just some random string.
假设您想发回一个实际的 JSON 而不仅仅是一些随机字符串。