[英]pass parameters from jquery to php
我有這個jQuery腳本
$(function() { // <----doc ready starts
$("#btn1").click(function(e) {
e.preventDefault();
var name = $("#id1").val();
var last_name = $("#id2").val();
var dataString = {'name=':name, 'last_name': last_name};
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'http://localhost/insert.php',
success: function(data) {
alert(data);
}
});
});
});
並且此php一個將參數從第一個腳本插入mysql數據庫:
<?php
$conn = mysqli_connect('localhost', 'root', '');
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$mysqli = new mysqli('localhost','root','','os');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$insert_row = $mysqli->query("INSERT INTO table_info (name, name2) VALUES($name, $last_name)");
if ($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}
else {
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
$mysqli->free();
$mysqli->close();
?>
當我嘗試運行它時,失敗並顯示以下錯誤:
注意:未定義的索引:第3行的C:\\ wamp \\ www \\ insert.php中的名稱
注意:第4行的C:\\ wamp \\ www \\ insert.php中的未定義索引:last_name
錯誤:(1064)您的SQL語法有錯誤; 檢查與您的MySQL服務器版本相對應的手冊以在第1行的')'附近使用正確的語法
這里出了什么問題,對不起愚蠢的問題,這是我第一次使用php和jQuery。
您沒有為AJAX調用提供dataString
變量,因此沒有數據被發送。 您需要將其添加到$.ajax
的data
屬性中:
$("#btn1").click(function(e) {
e.preventDefault();
var name = $("#id1").val();
var last_name = $("#id2").val();
var dataString = { 'name': name, 'last_name': last_name };
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'http://localhost/insert.php',
data: dataString,
success: function(data) {
alert(data);
}
});
});
請注意,我還修復了對象定義中的name=
typo。
生成有效的dataString
使用-
var dataString = "{'name=':"+name+", 'last_name': "+last_name+"}";
並將其傳遞給通話-
$.ajax({
type: 'POST',
data: dataString,
dataType: 'json',
url: 'http://localhost/insert.php',
success: function(data) {
alert(data);
}
});
您正在嘗試從$_POST
讀取內容,但您正在發出GET請求。
根據規范,JSONP 始終是 GET。 您不能使用該技術發出POST請求。
type: 'POST',
因為您說的是dataType: 'jsonp',
您還嘗試從name
讀取,但已將字段name=
稱為。 您需要始終使用相同的名稱。
當您收到響應時,您將得到一個錯誤,因為您的PHP腳本未使用JSONP進行響應。
您需要有header("Content-Type: application/javascript");
然后是以下內容:
echo $_GET['callback'] . "(" . json_encode($your_response) . ");";
…但是您應該通過清理回調名稱來增加對Rosetta漏洞的保護。
或者,刪除dataType: 'jsonp',
並添加header("Content-Type: text/plain");
到PHP。
在此行:type:'POST'之后,添加此行:data:dataString,
`enter code here`try to change the ajax call like this
`enter code here`$(function() { // <----doc ready starts
`enter code here` $("#btn1").click(function(e) {
`enter code here` e.preventDefault();
var name = $("#id1").val();
var last_name = $("#id2").val();
var dataString = {'name=':name, 'last_name': last_name};
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'http://localhost/insert.php',
data: JSON.stringify(dataString),
success: function(data) {
alert(data);
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.