【问题标题】:PHP Call with Ajax使用 Ajax 调用 PHP
【发布时间】:2026-02-07 13:10:01
【问题描述】:

我必须调用这个 php 文件

<?php
session_start();
require 'connect.php';

//Prendo le tre variabili dalla form
if(isset($_POST['Titolo'])) {
    $title_rew = $conn->real_escape_string($_POST['Titolo']);
}

if(isset($_POST['Voto'])) {
   $voto_rew = $conn->real_escape_string($_POST['Voto']);
}

if(isset($_POST['Review'])) {
    $review_rew = $conn->real_escape_string($_POST['Review']);
}

if(isset($_POST['ID_locale'])) {
    $id_rew = $conn->real_escape_string($_POST['ID_locale']);
}

$current_date = date('Y-m-d');

$sql = "INSERT INTO recensione (Titolo_R, Voto_R, Commento_R, IDnegozio_R, Email_R, Utente_R, Data_R) 
        VALUES ('$title_rew', '$voto_rew', '$review_rew','$id_rew','".$_SESSION['emailSessione']."','".$_SESSION['usernameSessione']."','$current_date')";

$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//Chiudo la connessione
$conn->close(); 

header("location:..\locals_page.php");
?>

我试过了

$("#submit_review").unbind().click(function() {
var chx = document.getElementsByName("Voto");
for (var i=0; i<chx.length; i++) {
   // If you have more than one radio group, also check the name     attribute
   // for the one you want as in && chx[i].name == 'choose'
   // Return true from the function on first match of a checked item
   $.post("php/insert_comment.php" );
     return true;

}
 // End of the loop, return false
 alert("Seleziona almeno il voto!");
return false;
});

但它不起作用。这很奇怪,因为有一个按钮提交和一个

 <form role="form" id="review-form" method="post" action="php/insert_comment.php">

它正在工作。 但现在我必须在没有按钮类型“提交”的情况下执行此操作

提前谢谢大家

【问题讨论】:

  • 首先你的代码是在php还是ajax上工作?我认为 $.post("php/insert_comment.php" );返回真;不起作用,因为在提交表单操作属性时将您的数据重定向到该 url,然后我认为您的点击事件无法正常工作

标签: javascript php jquery ajax post


【解决方案1】:

试试这个

$.ajax({
    url : "php/insert_comment.php",
    type : "post",
    data : $("#review-form").serialize();
    success : function(data){
        alert(data); // show when ajax return response from php script
    }
})

【讨论】:

    【解决方案2】:

    对于该按钮上注册的 onclick 事件并使用 jquery 发送 ajax 请求

    $.ajax({
    type:'POST',
    url : "your url",
    data : $('form').serializeArray(),
    cache: false,
    success:function(response){
    console.log(response) // your result from php
    }
    })
    

    【讨论】:

      【解决方案3】:

      单引号将 $ 视为字符串

      $sql = "INSERT INTO recensione (Titolo_R, Voto_R, Commento_R, IDnegozio_R, Email_R, Utente_R, Data_R) 
          VALUES ('".$title_rew."', '".$voto_rew."', '".$review_rew."','".$id_rew."','".$_SESSION['emailSessione']."','".$_SESSION['usernameSessione']."','$current_date')";
      

      【讨论】: