从javascript获取数据到php,并将其用于从mssql获取数据


getting data from javascript to php and using it in getting data from mssql

hi我有下面的代码,它首先将值从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);

要从服务器获得响应,不应该发出两个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);

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

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

在"key_name"上,您可以写入要在php中使用的名称。然后,在您的php代码中,您可以使用$_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