【问题标题】:getting data from javascript to php and using it in getting data from mssql从 javascript 获取数据到 php 并使用它从 mssql 获取数据
【发布时间】:2015-12-22 07:45:43
【问题描述】:

嗨,我有以下代码,它首先将值从 js 文件传递​​给 php

function calldata(value) {
    alert(value);
jQuery.ajax({
    url: "data3.php",
    type: 'post',
    data: value,

    dataType: 'json',
    success: function()
    {
       alert("hi");
    }
});
    var z = "<table>";

    jQuery.ajax({
        url: "data3.php",
        async: false,
        cache: false,
        dataType: "json",
        success: function(response) {
            alert(response);
            var p = 10;
            var j = 0;
            var m;
            z = z + "<tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>lunch</th><th>5</th><th>6</th><th>7</th><th>8</th></tr>";
            var k = response.length;
            if (k > 10)
                m = k / 10;
            for (var o = 0; o < m; o++) {
                z = z + "<tr>";

                for (j; j < p; j++) {
                    var obj = response[j];
                    var go = obj.subject;
                    z = z + "<td>" + go + "</td>";

                }
                z = z + "</tr>";

                p = p + 10;
            }
            z = z + "</table>";
            document.getElementById("jumbo").innerHTML = z;
        }



    });

首先,我试图通过 ajax 将 calldata 函数中的值发送到 php 并像这样接收它 $variable = $_POST['value'];

并尝试编写一个选择查询来获取数据 $sql = "SELECT * from class1 where class=$variable";

但它不起作用,谁能告诉我正确的程序或这段代码有什么问题,因为我没有收到错误

我的 php 代码是:

$serverName = "esdapocnv01";
$connectionInfo = array( 'Database'=>'INDUS', 'UID'=>'testuser', 'PWD'=>'notmyrealpassword');

$conn = sqlsrv_connect( $serverName, $connectionInfo );

if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));

    echo "Connection could not be established.<br />";

}
$variable = $_POST['value'];

$sql = "SELECT * from class1 where class=$variable";

$emp1array=array();
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    //example of adding extra data if required
    $emp1array[]=$row;

}

echo json_encode($emp1array);


sqlsrv_free_stmt( $stmt);

【问题讨论】:

  • 您在调试代码时尝试了什么?
  • 是的,我试过没有错误
  • 我使用 chrome 调试器显示没有错误
  • 调试包括检查值、控制流。例如,您是否检查过您的$_GET['value'] 的值是多少?
  • 这是逻辑错误。您应该只进行一次 ajax 调用:PHP 处理请求并在 that 请求上发送响应。现在你调用 PHP 两次,但第二次没有传递任何信息,所以它不能给出一个好的答案,但这就是你离开的答案。加入两个ajax请求

标签: javascript php jquery sql-server ajax


【解决方案1】:

要从服务器获得响应,您不应发出两个 Ajax 调用。这个想法是你通过 Ajax 发出一个请求,并在 success 处理程序中得到响应。

所以,加入两个 Ajax 调用,如下所示:

function calldata(value) {
    alert(value);
    jQuery.ajax({
        url: "data3.php",
        type: 'post',
        //async: false, // why? Don't block your browser! Leave this out.
        data: {value: value}, // key/value, so PHP finds your data as "value"
        cache: false,
        dataType: "json",
        success: function(response) {
            alert(response);
            var p = 10;
            var j = 0;
            var m; 
            var z = "<table>"; // moved here
            z = z + "<tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>lunch</th><th>5</th><th>6</th><th>7</th><th>8</th></tr>";
            // Note: z needs one more column (10 in total!)
            var k = response.length;
            // if (k > 10) // remove this IF, you need a value in ALL cases.
                m = k / 10;
            for (var o = 0; o < m; o++) {
                z = z + "<tr>";
                for (j; j < p; j++) {
                    var obj = response[j];
                    var go = obj.subject;
                    z = z + "<td>" + go + "</td>";
                }
                z = z + "</tr>";
                p = p + 10;
            }
            z = z + "</table>";
            document.getElementById("jumbo").innerHTML = z;
        }
    });
    // Note that any code that follows here will be executed 
    // before the above success handler will be called.
}

还要检查上述代码中的一些其他建议更改(已注释)。

在 PHP 中,我还建议进行一些修改(在代码中注释),最重要的是,您当前的代码容易受到 SQL 注入的攻击,您应该确保所有输出都是 JSON 编码的(甚至是错误消息):

// indicate that you're going to return JSON:
header('Content-Type: application/json');

$serverName = "esdapocnv01";
$connectionInfo = array( 'Database'=>'INDUS', 'UID'=>'testuser', 'PWD'=>'notmyrealpassword');
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
    // json_encode your errors:
    die( json_encode(sqlsrv_errors(), true)); 
    // removed echo, because code after die is never executed
}
// check if value is posted:
if (!isset($_POST['value'])) {
    // json_encode error message:
    die(json_encode(["error" => "value is missing"]));
}

$variable = $_POST['value'];

// prevent SQL injection, use parameters (?)
$sql = "SELECT * from class1 where class=?";

$emp1array=array();
// pass variable in a parameter array:
$stmt = sqlsrv_query( $conn, $sql, array($variable)); 
if( $stmt === false) {
    // json encode the error list:
    die( json_encode( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    //example of adding extra data if required
    $emp1array[]=$row;
}

echo json_encode($emp1array);

sqlsrv_free_stmt( $stmt);

【讨论】:

  • 它在 chrome 中再次调试时无法正常工作,它没有进入 ajax 调用
  • “不进入”是什么意思?
  • 我正在向行添加断点并观察程序如何在其警报值直接变为 z = z + "" 时逐步运行;这一行
  • 这样就证明了 Ajax 请求和响应正在发生alert(response) 显示什么?
  • 响应 [Object0: "42000"1: 1022: "[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'A' 附近的语法不正确。"SQLSTATE: "42000" 代码: 102 消息:“[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'A' 附近的语法不正确。”proto:对象]
【解决方案2】:

您的value 变量是JSON object?如果不是,您必须像这样发送变量:

jQuery.ajax({
    url: "data3.php",
    type: 'post',
    data: { key_name: value },
    dataType: 'json',
    success: function()
    {
       alert("hi");
    }
});

在“key_name”上,您可以在php 中写入您想要使用的名称。然后在您的phpcode 中,您可以使用$_POST["key_value"] 访问该值。

编辑:

我写了下一段代码来测试它:

index.php

<body>
    <input type="button" class="send" value="send" />
    <script>

        $(".send").on("click", function() {

            $.ajax({
                url: "test.php",
                type: "post",
                data: "world",
                dataType: "json",
                success: function(response) {
                    console.log(response);
                }
            });

        })

    </script>
</body>

test.php

var_dump($_POST);
var_dump($_GET);

在第一次执行时,发送到服务器的值是 string data: "world",结果是:

array (size=1)
  empty
array (size=0)
  empty

在第二次执行时,发送到服务器的值是 json object data: { value: "world" }

这就是我从服务器得到的:

array (size=1)
  'value' => string 'world' (length=5)
array (size=0)
  empty

【讨论】:

  • 不,它不是一个 json 对象,你能告诉我在同一个函数中使用两个 ajax 调用会产生问题吗??
  • 我写了一个示例来测试代码,如果我使用json object,我会得到响应
  • 如果有问题,你能看看我的php代码吗??
猜你喜欢
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 2013-02-11
相关资源
最近更新 更多