如何在jQuery中的函数调用中传递2个值

How to pass 2 values in function call in jQuery

本文关键字:2个值 函数调用 jQuery      更新时间:2023-09-26

嗨,我有jQuery函数,在其中我调用了servlet,并传递了2个值,但它显示NullPointerException。我不知道为什么,但我认为我在其中提出论点是错误的。

我的代码:

function addProductById(pId,pMqty){
                $.getJSON("addtocart?pid=" + pId + "&minqty="+ pMqty +"&rand=" + Math.floor((Math.random()*100)+1), function(json) {
                    alert(json.msg);
                });
            }

在这里,我将2个变量pId和pMqty传递给servlet addtocart,但在servlet中没有接收到。知道它为什么不去那里吗?

我还将此函数调用为JavaScript,点击按钮:

onclick='addProductById(" + this.id + ","+ this.minqty +");'

能帮忙吗?

Java脚本代码:

tableRow: function tableRow(product){
    this.id = product.pId;
    this.image = product.pImage;
    this.name = product.pName;
    this.price = product.pPrice;
    this.feature = product.pFeature;
    this.minqty = product.pMqty;
    var image = "<div class='mainitemlist'><div class='mainitemlistimage'><a href='product?pid=prdID'><img src='product_images/prdIMAGE' height='125px' width='100px' style='border-radius:2px;'></a></div>";
    var name = "<div class='mainitemlistname'><div align='center'><a href='product?pid=prdID' style='color: #9caeb9;text-decoration: none;'>prdNAME</a></div></div>";
    var price = "<div class='mainitemlistprice'><div align='center'>prdPRICE</div></div>";
    var features = "<div class='mainitemlistfeatures'><div align='center'> <!--prdFEATURE-->MOQ : prdMINQTY</div><div align='center'><button type='button' style='display: none;margin-top: 5px;' class='btn btn-primary' onclick='addProductById(" + this.id + ","+ this.minqty +");'>Add To Cart</button></div></div></div>";

    this.generateHTML = function generateHTML(){
        html = "";      
        html += image.replace("prdIMAGE", this.image).replace("prdID", this.id);
        html += name.replace("prdNAME", this.name).replace("prdID", this.id);
        html += price.replace("prdPRICE", this.price);
        html += features.replace("prdFEATURE", this.feature).replace("prdMINQTY", this.minqty);;
        return html;        
    };
}

为了使用JavaScript显示数据,这里container是div,我只在jsp页面中调用了这个div

display: function display(){        
    var node = document.getElementById('container');
    while (node.hasChildNodes()) {
        node.removeChild(node.firstChild);
    }
    var html = "";
    for(var i = 0; i < catalogue.product.length; i++){              
        var tableRow = new catalogue.tableRow(catalogue.product[i]);  
        html += tableRow.generateHTML();    
    }
    document.getElementById('container').innerHTML = html;
}

您可以这样做:-

onclick='addProductById("' + this.id + '","' + this.minqty +'");'

onclick属性中的单引号没有正确闭合,这就是为什么这些值不起作用的原因。

并测试如下:-

function addProductById(pId, pMqty) {
    // You can test the values here
    alert(pId + ', ' + pMqty);
    // your code here..
}