从javascript获取数据到php并使用它从mssql获取数据

时间:2015-12-22 07:45:44

标签: javascript php jquery sql-server ajax

嗨,我有以下代码,首先将值从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);

2 个答案:

答案 0 :(得分:0)

您的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

答案 1 :(得分:0)

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