在这里,我有这个jQuery代码,它将值传递给处理数据库查询的php文件。
$("#item-input-form__complete-form-btn").click(function(){
var invoiceInfo = {
"date" : $("[name=datepicker]").val(),
"op_id" : 11111,
"invoice_number" : $("[name=invoice]").val(),
"vendor_id" : 33333
};
var jsonResult = $('#added-items__table').tableToJSON();
$.ajax({
type: "POST",
url: "insert_items_to_db.php",
data: {QUERY_TYPE:"INSERT",
INVOICE_INFO:invoiceInfo,
JSON_RESULT:jsonResult},
success: function(){alert("SUCCEEDED");},
error: function(xhr, textStatus, error){
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
这里我有php文件处理传递的参数并运行查询。
insert_items_to_db.php ::
<?php
include_once('models/dbapi.php');
$query_type = $_REQUEST["QUERY_TYPE"];
$invoice_info = $_REQUEST["INVOICE_INFO"];
$product_json = $_REQUEST["JSON_RESULT"];
$DB = new DBAPI();
$DB->connectTo('BBY');
$DB->insertDataIntoStockMasterTable($invoice_info, $product_json);
$DB->insertDataIntoStockDetailTable($invoice_info, $product_json);
$DB->disconnect();
?>
运行查询的DBAPI类中的方法看起来像这样。
dbapi.php ::
function insertDataIntoStockMasterTable($invoice_info, $product_json)
{
$invoice_date = $invoice_info['date'];
$invoice_number = $invoice_info['invoice_number'];
$op_id = $invoice_info['op_id'];
$vendor_id = $invoice_info['vendor_id'];
$today_date = date("Y-m-d");
$invoice_date = date("Y-m-d", strtotime($invoice_date));
$total_amt = 0;
for($i = 0; $i < count($product_json); $i++)
{
$total_amt += $product_json[$i]['Extended Price'];
}
$query ="INSERT INTO stock_master (sm_date, sm_invoice_no, sm_vendor_cd, total_amt, op_id, op_date)
VALUES('$invoice_date', $invoice_number, $vendor_id, $total_amt, $op_id, '$today_date')";
$result = mssql_query($query, $this->selected_hannam_db_server);
return $result;
}
这里的问题是......我无法弄清楚如何检查查询是否已崩溃。在这种情况下,jquery应弹出一个msg框,告诉用户将数据插入db失败。
如何将错误消息从php传递给jquery?
答案 0 :(得分:2)
这样的事情对你有用。
if( $DB->insertDataIntoStockDetailTable($invoice_info, $product_json) ) {
$result['result'] = true;
$result['error'] = '';
} else {
$result['result'] = false;
$result['error'] = 'Insert failed.';
}
header('Content-Type: application/json');
$data = json_encode($result);
echo $data;
$.ajax({
type: "POST",
url: "insert_items_to_db.php",
data: {QUERY_TYPE:"INSERT",
INVOICE_INFO:invoiceInfo,
JSON_RESULT:jsonResult},
success: successResponseHandler,
error: function(xhr, textStatus, error){
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
function successResponseHandler(data, textStatus, jqXHR) {
if( data['result'] == true){
// DO Something here
} else {
// Display the error message with text from data['error']
}
}