I got the following piece of code

function pushJsonData(productName) {
    $.ajax({
        url: "/knockout/SaveProduct",
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        data: " { \"Name\" : \"AA\" } ",
        async: false,
        success: function () {
            loadJsonData();   
        },
        error: function (jqXHR, textStatus, errorThrown) {
          alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
        }
    });
}

注意,我硬编码了数据值.数据被很好地推入数据库.然而,我一直在犯错误

parsing error syntax error unexpected end of input

I am sure my data is in correct JSON syntax. When I checked with on Network of Chrome inspector the saveProduct request showed the data is correct.

{ "Name": "AA" }

This POST request did not have response. So I am clueless as to where the parse error was coming from. I tried using FireFox browser. the same thing happened.

谁能告诉我出了什么问题吗?

Thanks,

附笔.

namespace MvcApplJSON.Controllers
{
    public class KnockoutController : Controller
    {
        //
        // GET: /Knockout/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetProductList()
        {
            var model = new List<Product>();
            try
            {
                using (var db = new KOEntities())
                {
                    var product = from p in db.Products orderby p.Name select p;
                    model = product.ToList();
                }
            }
            catch (Exception ex)
            { throw ex; }
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public void SaveProduct (Product product)
        {
            using (var db = new KOEntities())
            {
                db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
                db.SaveChanges();
            }
        }
    }
}

推荐答案

我不能确定问题出在哪里.可能是一些坏性格,可能是你在开始和结束时留下的空间,不知道.

无论如何,您不应该像以前那样将JSON硬编码为字符串.相反,将JSON数据发送到服务器的正确方式是使用JSON序列化程序:

data: JSON.stringify({ name : "AA" }),

现在,在服务器上,还要确保您具有期望接收以下输入的正确视图模型:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there's one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most cases, usually you don't need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

我怀疑您在这里遇到的问题是您的服务器没有返回有效的JSON.它返回一些ViewResult或PartialViewResult,或者您试图在控制器操作中手动手工创建一些损坏的JSON(显然,除了使用JsonResult之外,您永远不应该这样做).

我还注意到一件事:

async: false,

请避免将此属性设置为False.如果将此属性设置为false,则会在请求的整个执行过程中冻结客户端浏览器.在这种情况下,你可以只提出一个正常的请求.如果您想使用Ajax,请开始考虑异步事件和回调.

Json相关问答推荐

如何将加权边列表导出到JSON树?

在Reaction中从JSON文件中筛选数组

将 std::可选值存储到 json 文件 C++

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

爆炸没有数组的 struct pyspark

从 oracle 数据库中的 json blob 打印值

JSON 的自定义编组器,可以是字符串或 map[string]string / map[string]bool

如何通过 jolt 将一个对象中的键和值添加到数组中的每个对象中

从ruby中的json获取特定的键值

杰克逊 2.0 和 Spring 3.1

如何使用法语口音对数组进行 json_encode?

未捕获的类型错误:无法读取 null 的属性props

如何一次加载无限滚动中的所有条目以解析python中的HTML

苗条的 JSON 输出

IE中Json响应下载(7~10)

JSON对象中的JavaScript递归搜索

Jsonpath 与 Jackson 或 Gson

使用杰克逊创建一个 json 对象

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

如何使用 SwiftyJSON 遍历 JSON?