[英]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.