简体   繁体   English

这个JQuery AJAX代码有什么问题

[英]What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. 我在使用AJAX代码时遇到了一些问题。 I was using MVC3 for our project. 我在我们的项目中使用了MVC3。 My requirement is bind the dropdown value using AJAX when page load. 我的要求是在页面加载时使用AJAX绑定下拉值。 What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. 加载页面时,AJAX请求会正确发送到控制器,然后返回AJAX函数,并在下拉列表中绑定确切的值,这会发生什么。 But sometimes (When page refreshed or first time load) its not binding retrieved value. 但是有时(当页面刷新或首次加载时)其未绑定的检索值。 Rather its showing default value. 而是显示默认值。 Pls see my code and suggest me where i am doing wrong. 请看我的代码并建议我在哪里做错了。

Edit: Even i tried to use async property to false. 编辑:即使我试图使用async属性为false。 Its not at all send to the controller action method for getting the data. 它根本不发送到控制器获取数据的动作方法。

Code

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: '@Url.Action("GetUser", "Invoices")',
            data: "{'id':" + JSON.stringify(currval) + "}",
            dataType: "json",
            async: true,
            success: function (data) {
                $("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
                $(this).val(data.Value);
            }
        });

Thanks, 谢谢,

You are declaring your data property incorrectly. 您在错误地声明您的data属性。 Try this: 尝试这个:

data: { id: currval },

Let's say your Action method is below 假设您的Action方法在下面

public JsonResult hello(int id)
{
    return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}

and JQuery should be like below 和JQuery应该像下面

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        var currval = 2;
        $.ajax({
            url: 'URl',
            async: true,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ id: currval }),
            success: function (data) {
            }
        });
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM