最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to pass Json string as a javascript method parameter - Stack Overflow

programmeradmin2浏览0评论

I formed a Json String.

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

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

I formed a Json String.

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

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

Share Improve this question edited May 31, 2013 at 11:10 Isaac 11.8k5 gold badges35 silver badges45 bronze badges asked May 31, 2013 at 11:01 user2440125user2440125 311 gold badge1 silver badge3 bronze badges 1
  • Why are you handling the click on a submit input ? Don't you want to handle the submit event on the form instead ? – Denys Séguret Commented May 31, 2013 at 11:07
Add a ment  | 

1 Answer 1

Reset to default 4

You could parse it using

var product = JSON.parse(jsonProduct);

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

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 :

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

评论列表(0)

  1. 暂无评论