如何将 Json 字符串作为 javascript 方法参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16855753/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:15:07  来源:igfitidea点击:

How to pass Json string as a javascript method parameter

javascriptjson

提问by user2440125

I formed a Json String.

我形成了一个 Json 字符串。

var jsonProduct = "{Product:'" + Details[0] + "',Brand:'" + Details[1] + "',Model:'" + Details[2] + "',Price:'" + Details[3] + "'}"

<input class="button black" type="submit" value="Add To Cart" onclick="return addOrderItem(' + jsonProduct + ')" />

How to pass this 'jsonproduct to javascript function addOrderItem as follows

如何将这个 'jsonproduct 传递给 javascript 函数 addOrderItem,如下所示

function addOrderItem(product)
{
    cartproduct[cartproduct.length] =  " + product + ";
    //cartproduct[cartproduct.length] = " + {Product:'1001',Brand:Dell',Model:'Inspiron',Price:'25000'} + ";
}

When I pass product as parameter it is not working

当我将产品作为参数传递时,它不起作用

回答by Denys Séguret

You could parse it using

你可以解析它使用

var product = JSON.parse(jsonProduct);

but you don't have to use JSON at all. Do this :

但您根本不必使用 JSON。做这个 :

var product = {
    Product: Details[0], Brand:Details[1],
    Model:Details[2], Price:Details[3]
};
addOrderItem(product);

If you want to call this from an input click, you can bind the call using

如果你想从输入点击调用它,你可以使用绑定调用

onclick="return addOrderItem(product)"

or, better, give an id to your element and then bind the event handler from the JS code :

或者,更好的是,为您的元素提供一个 id,然后从 JS 代码绑定事件处理程序:

<input id=submit class="button black" type="submit" value="Add To Cart">
<script>
    document.getElementById('submit').onclick=function(){addOrderItem(product)};
</script>