jquery - 多次使用 jQuery 的 ajax 和数据库查询

标签 jquery mysql ajax database

我遇到的问题是了解如何使用 jQuery ajax 功能为数据库查询的多个场景返回结果。

这是我目前的代码...这是 ajax 函数:

function checkDB(code)
{

  $.ajax({
  type: "POST",
  url: "<?php bloginfo('template_url'); ?>/profile/check_code.php",
  data: 'code='+code,
  datatype: "html",
  success: function(result){

       if(result == 0)
       {
        $('#success').html( code + ' already exists.');
       // alert('success');//testing purposes
       }
       else
       {
        $('#err').html(  code + ' isnt in the database!!.');
        //alert('fail');//testing purposes
       }

alert(result);     


      }
  })

}

这使用以下形式在提交时运行函数:

   <form method="post" name="sc_ajax" onsubmit="checkDB(document.sc_ajax.sc_voucher_code.value); return false;">
         ...
   </form>

在 check_code.php 中运行数据库查询:

    $code = mysql_real_escape_string($_POST['code']);  

$resultcode = mysql_query('select * from wp_scloyalty where code = "'. $code .'"' ) or die(mysql_error());  
if(mysql_num_rows($resultcode)>0){
    //Exists  
    echo 0;  
}else{  
    //Doesnt Exist
    echo 1;  
}  

到目前为止,我的工作是收到一条消息,说明输入的代码是否存在于数据库中。

我的问题是我将如何着手对查询做更多的事情。例如,有更多的“if 语句”来测试数据库中的更多列?我想说“如果代码已经在数据库中,如果‘兑换’列设置为 1(默认 0),则执行不同的操作”?

目前我只能根据 ajax 回复的功能(结果)输出内容,但是有没有更有效的方法来完成我所做的事情?还是让当前设置更灵活的更有效方式?

有点长的问题,抱歉,但我觉得我需要弄清楚一些事情,

谢谢大家:)

最佳答案

在我看来,您真正想要的是一种以 javascript 可以解释的方式将数据发送回客户端的方法。为此,我建议在 PHP 中使用 json_encode 将 JSON 发送回客户端。

如果您想学习如何正确使用 ajax,我会点击这些链接。你快到了。

http://www.w3schools.com/json/default.asp学习 JSON

在服务器端使用 json_encode。

http://php.net/manual/en/function.json-encode.php

关于jquery - 多次使用 jQuery 的 ajax 和数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9316455/

相关文章:

javascript - 将字符串植入 html 页面(具有挑战性)

PHP 和 MySQL 到 Android 的翻译

java - 如何在 Spring Prepared Statement 中传递 Java Date

c# - 无论如何在 ajax 调用中从 asp.net-mvc 中的服务器端异常返回原始文本而不是 html?

javascript - AJAX 查询 |访问返回的对象数据

javascript - 如何使用 JavaScript 触发模态框?

javascript - 使光标在计时器上透明(0.5)

javascript - jquery 在 mouseenter 上显示一个元素

c# - 用户友好的 Jenkins CI 作业计划格式

javascript - 在 jQuery AJAX 加载后重新触发某些脚本