[英]jQuery AJAX: Clarification on How to Pass Variable into AJAX GET Request
我正在查看有關實現jQuery ajax方法的一些Stack Overflow線程:
盡管此線程提供了一些非常好的信息,但我正在尋求澄清,以了解它是否確實可以完成我認為會做的事情。
我在jQuery click函數中具有ajax GET請求:
//click an image
$(".img_div").click(function() {
//get integer stored in element attribute and put it in variable
var altCheck = $(this).find('.modal_img').attr('alt');
//get MySQL data
$.ajax({
url: "get.php",
type: "get"
data: {
ajaxid: altCheck //variable from above - is this correct?
}
....
....
});
在get.php中 ,我希望像這樣使用變量:
$sql = "SELECT * FROM table WHERE screeningId = $ajaxid";
本質上,我想通過將變量傳遞到AJAX請求中來修改我的SQL語句,但是我不確定這是否完成。
在您的JavaScript中使用此
$.ajax({ url: 'get.php',
data: {'ajaxid':altCheck},
type: 'post',
dataType:'json'
});
並在您的get.php中使用
$ajaxid = $_POST['ajaxid'];
$sql = "SELECT * FROM table WHERE screeningId = $ajaxid";
就像我之前在評論中提到的那樣。 該代碼目前不安全。 回答您的原始問題。 是的,您可以在ajax調用中使用data屬性傳遞值。
引用:arkash anjum的答案
$.ajax({ url: 'get.php',
data: {'ajaxid':altCheck},
type: 'post',
dataType:'json'
});
並像這樣獲取get.php中的值
$ajaxid = $_POST['ajaxid'];
$sql = "SELECT * FROM table WHERE screeningId = $ajaxid";
但這意味着您正在向應用程序開放注入攻擊
解決方法之一是清理js屬性。 但這仍然不是萬無一失的解決方案。 您需要使用的是sql查詢中的一條准備好的語句,並使用該值分配ajax值,然后執行該語句。 最好同時使用消毒劑和預處理語句,以避免xss攻擊和sql注入攻擊
<?php
$stmt = $dbh->prepare("SELECT * FROM table WHERE screeningId = ?");
if ($stmt->execute(array($_POST['ajaxid']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
注意:我不了解php,所以某些語法可能不對。
參考准備好的聲明http://php.net/manual/en/pdo.prepared-statements.php
在URL中通過以下方式添加斜杠,
url: "get.php/" + altCheck;
並在get.php文件中以$ _GET ['altCheck']訪問
記住在GET方法中,我們需要在URL中傳遞數據。
編碼愉快!
這是一些樣板。(例如,我正在使用您的代碼。)
注意 :在為ajax請求批量發送數據時,應該使用POST方法,但是正如您提到的,要使用get
來發布數據,我已經使用過Get
,您可以將類型更改為Post
快速鏈接:用於ajax http://api.jquery.com/jquery.ajax/
使用PDOS https://www.w3schools.com/php/php_mysql_prepared_statements.asp
在js中:
$(".img_div").click(function(){
//get integer stored in element attribute and put it in variable
var altCheck = $(this).find('.modal_img').attr('alt');
// lets send data.
$.ajax({
url: "get.php",
type: "get",
datatype : "json",
data:{ ajaxid: altCheck } //this is valid to use as you already have variable of name altCheck in case of string it should be in double quotes.
},
success : function(data) // this will be called if ajax succeeds and data will hold the ref to your returned data if any.
{
// do whatever with data.
}, error : function(data) // error handler if any error occurs (failed ajax)
{
// do handle error here.
}
});
在PHP中:
$value = filter_var($_REQUEST["ajaxid"], FILTER_SANITIZE_STRING); // used REQUEST So get/post request wont matter.
$value = mysqli_real_escape_string($value);
$stmt = $conn->prepare("select from table where id = ?");
$stmt->bind_param("s",$value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.