mysql 데이터베이스에서 정보를 가져 오는 기능이 있습니다. 이 함수는 테스트를 거쳤으며 일반 html 양식 제출 버튼에서 호출 할 때 작동합니다. 그러나, 나는 아약스를 구현하려고 시도하고, 나는 똑같은 함수를 호출하지만, 작동하지 않는다. 나는 왜 그런지 모른다.ajax를 사용할 때 데이터베이스 기능이 작동하지 않습니다.
다음은 데이터베이스 기능입니다. 더 읽기 쉽도록 불필요한 코드를 제거했습니다.
function itemUPCsearch($upc)
{
$conn = localConnection();
$query = "SELECT Items.UPC, availability, description, price, brand, perqty, item_type, unit_type, size, discount, serv_per_cal, calories, calories_from_fat, total_fat, saturated_fat, trans_fat, cholesterol, sodium, total_carbohydrate, dietary_fiber, sugars, protein, vitamins, ingredients, full_image_path FROM Items LEFT JOIN Nutrition ON Items.UPC = Nutrition.UPC LEFT JOIN item_pic P ON P.UPC = Items.UPC WHERE Items.UPC = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "s", $upc);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $upc, $avail, $desc, $price, $brand, $perqty, $itype, $utype, $size, $discount, $servpercal, $cal, $calfromfat, $totfat, $satfat, $tranfat, $chol, $sod, $totcarb, $dietfib, $sugar, $prot, $vit, $ing, $image);
while(mysqli_stmt_fetch($stmt))
{
// Execution never makes it inside this loop
// Do stuff here (Code has been removed as it is not relevant
// To this question)
}
mysqli_stmt_close($stmt);
closeConnection($conn);
return $searchItems;
}
내가 알 수있는 한 모든 것이 괜찮은 것 같습니다. 나는 $ conn과 $ stmt에 print_r을했고, 나는 내가 기대했던 것을 되돌려 놓았다. 이것들을 working 함수에서 print_r과 비교해 보았습니다. 그리고 나는 같은 결과를 얻었습니다. 나는 execute 함수의 결과를 출력했고 사실을 리턴한다. 쿼리가 일반 양식 제출과 함께 작동했을 때부터 변경되지 않았습니다. 전달 된 값 $ upc가 정확하며 데이터베이스에이 항목이 있습니다. 사실, mysql에 upc 값을 가진 쿼리를 복사하여 붙여 넣을 때 올바른 결과를 얻었습니다. 비록 동일한 upc에서 전달되는 동안 양식 포스트를 사용하여이 동일한 함수를 호출 할 때 함수를 만들지 만 함수가 while 루프 내부에서 사용하지는 않습니다. 여기
내 아약스 스크립트입니다 :function loadCart(itemID,cart) {
var httpRequest;
makeRequest(itemID,cart);
function makeRequest(itemID,cart) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :(Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = fillTheCart;
httpRequest.open('GET', "../controller/addToCartAjaxScript.php?upc="+itemID+"&cart="+cart,true);
httpRequest.send();
}
function fillTheCart() {
try {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
document.getElementById("cartView").innerHTML=httpRequest.responseText;
}
else {
alert('There was a problem with the request.');
}
}
}
catch(e) {
alert('Caught Exception: ' + e.description);
}
}
}
그리고 여기에 스크립트입니다 아약스 전화 :
<?php
//include_once '../databaseFunctions/session.php';
include_once '../databaseFunctions/databaseConnection.php';
include_once '../databaseFunctions/databaseFunctions.php';
include_once '../controller/TableControllerHeader.php';
include_once '../controller/ShoppingCartControllerHeader.php';
include_once '../controller/UserControllerHeader.php';
include_once '../controller/functions.php';
$upc = intval($_GET['upc']);
$cartName = $_GET['cart'];
$cart = new Cart();
$customer = new Customer();
print $upc;
if($upc != ""){
$cart = addToCart($upc,$cartName);
}
else{
if(isset($_SESSION['customer'])){
$customer = unserialize($_SESSION['customer']);
$cart = $customer->FindCart($cartName);
if($cart = null){
$cart = new Cart();
}
}
}
print $cart->PrintCart();
?>
내가 때문에 인쇄 $ cart-> PrintCart, 아약스가 작동하는지 알고(); 아약스에 의해 호출 된 스크립트의 끝 부분에 그것이 예정된 것을 인쇄하고 ID가 "cartView"인 요소에 배치됩니다. 데이터베이스 기능에서 가져온 데이터를 포함하지 않습니다.
localConnection(); itemUPCsearch 함수에서 호출되는 함수는 ajax가 호출하는 스크립트의 시작 부분에 포함 된 databaseConnection.php 스크립트에 있습니다. 나는이 스크립트를 메인 스크립트에서도 호출하고 있지만, 이것이 문제라고 생각하지 않는다. 어떤 충돌 오류도 발생하지 않으며 include 문을 제거하면 localConnection() 함수를 찾을 수 없다는 오류가 발생합니다.
함수의 모든 내용이 정확하다고 생각하면 무엇이 잘못되었는지 이해하지 못합니다. 어떤 도움이라도 대단히 감사하겠습니다!
편집
나는 데이터베이스 기능의 각 함수 호출 후 mysql_error를()를 인쇄하고 그 중 한 후 오류 메시지를 받았습니다 없다.
문제의 범위를 좁히기 위해 디버깅을 시도한 적이 있습니까? 왜 코드에서 가능한 DB 오류를 처리하지 않습니까? –
@Mike Brant 필자가 시도하지 않은 다른 디버깅 방법을 알지 못합니다. 위에 언급하지 않은 다른 어떤 것들을 시도해 볼 수 있습니까? – Jason247
데이터베이스 함수에서 각 함수 호출 후에 mysql_error()를 출력했으며 그 중 하나 다음에 오류 메시지가 표시되지 않습니다. – Jason247