簡體   English   中英

jQuery $ .ajax()函數未正確運行POST請求

[英]JQuery $.ajax() function not running POST request accurately

我有以下HTML

<select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select>

<input type="text" id="prd_price" title="prd_price1" name="prd_price">

我從系統數據庫中動態更新了<select></select>並添加了一些產品及其各自的ID。 我編寫了一個JQuery / Javascript函數,該函數假定使用$ .ajax()從選擇菜單將該產品ID發送到php頁面,並從數據庫中獲取其相應價格,並用該價格填充<input>

我的jQuery如下:

function getpricefromselect(x){

    var value=$(x).val();
    var title=$(x).attr('title');

    if(title.length == 9){
        var len=Number((title).substr(-1,1));    

        if(value.length>0){
            $.ajax({
                type:'POST',
                url:'getpricefromselect.php',
                data:{productid: value},
                success:function(data){
                    $("[title=prd_price"+len+"]").val(data).show();
                }
            })
        }
    }
};

並且“ getpricefromselect.php”中的php如下:

$productid="";
$Price="";
$productid=$_POST["productid"];
$selectProduct="SELECT InventoryProductPrice FROM InventoryProductsList WHERE InventoryProductID = '{$productid}';";
$selectProduct_query = mysqli_query($connection, $selectProduct);
if(!$selectProduct_query){
    die ("Database query for selecting Product Price failed.");
}
while ($selectProduct_array = mysqli_fetch_assoc($selectProduct_query)){
    $Price= $selectProduct_array["InventoryProductPrice"];
}
echo $Price;

問題是當我從PHP文件中回顯$ Price時,jQuery $ .ajax()用空白項目填充<input> ,但是如果我回顯$ productid,它將使用准確的productid填充<input> 我的產品ID對每個產品都是唯一的,當我在與javascript相同的頁面上調用相同的php函數時,它將返回准確的價格。 誰能告訴我,如果從PHP回顯了$ Price,為什么$ .ajax()返回一個空白項,而從php回顯了$ productid卻沒有給出一個空白項。

如果我將實際產品ID手動添加到php文件,則php回顯的$ Price是准確的。 如果它是通過POST從$ .ajax()發送的,則它似乎沒有被php正確運行。

如果您使用開發人員控制台查看查詢帶來了什么答案,或者ajax請求遇到了什么問題,那將是很好的。

另一方面,您可以嘗試這樣

$(function(){
    $("#options").change(function()){
        getpricefromselect($(this).val());
    });
})


function getpricefromselect(x){

    var obj = {
        productid:x
    }

    $.post('getpricefromselect.php',obj)
    .done(function(resp){
        if(resp){
            $("#prd_price").val(resp)
        }
    })
    .fail(function(err){

    })

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM