使用jquery ajax传递数据

Tyl*_*den 12 ajax asp.net-mvc jquery

我总是得到'错误'警告,我无法弄清楚出了什么问题.我只是试图找回我发送的字符串("testexpression").它必须与数据部分有关,因为没有参数它可以工作.

这是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>
Run Code Online (Sandbox Code Playgroud)

这是控制器:

    public class GetMeaningController : Controller
{
    //
    // GET: /GetMeaning/

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(string expression)
    {

        return Json(expression, JsonRequestBehavior.AllowGet);

    }

}
Run Code Online (Sandbox Code Playgroud)

(更新:类型是发布的,我只是尝试使用get,我把它留在了)

小智 16

您需要以字符串/ 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');
    }
})
Run Code Online (Sandbox Code Playgroud)