简体   繁体   English

使用Jquery ajax函数时,错误'缺少:在属性id之后'

[英]Error ' missing : after property id' when using Jquery ajax function

In the following code, I'm trying to send a key-value pair and I always get the error: 在下面的代码中,我正在尝试发送一个键值对,我总是得到错误:
" missing: after property id " “失踪:财产ID后”

$(".general").change(function () {
  fields = { $(this).attr('id') : "1" };
  $.ajax({
   type: "POST",
   url: "ajax/update_general.php",
   data: { fields: fields },
   dataType: "json",
   });
})

I've figured that what causes the problem is: 我认为导致问题的原因是:

$(this).attr('id')

But I have no clue why. 但我不知道为什么。 I've tried to first assign $(this).attr('id') to a variable, and put the variable in the ajax call, but that didn't help. 我试图首先将$(this).attr('id')分配给变量,并将变量放在ajax调用中,但这没有帮助。 How can I fix that? 我该如何解决这个问题?
Thank you! 谢谢!

It's a syntax error. 这是一个语法错误。 You can't use the return value of a function call as a property name. 您不能将函数调用的返回值用作属性名称。

You can, however, use that return value in bracket notation after initializing the object: 但是,您可以初始化对象以括号表示法使用该返回值:

  fields = {};
  fields[$(this).attr('id')] = '1';

When declaring object with {} syntax, ONLY strings (like {'foo':1}) or bare string is allowed ({foo:1}) 使用{}语法声明对象时,只允许字符串(如{'foo':1})或裸字符串({foo:1})

You should write something like this: 你应该写这样的东西:

var fields = {};
fields[$(this).attr('id')] = 1;

Change this line: 改变这一行:

fields = { $(this).attr('id') : "1" };

to this: 对此:

fields = $(this).attr('id') || "1";

That's if you intended to have something like a default value. 如果您打算使用默认值,那就是这样。

If you want an object, use this: 如果你想要一个对象,请使用:

fields[$(this).attr('id')] = "1";

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

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