使用 ajax 将 JavaScript 数据传输到 PHP


Use ajax to transport JavaScript data to PHP

raise.js:
window.onload=init;
function init(){
    var submit=document.getElementById("submit");
    submit.onclick=sub;
}
function sub(){
    var url="raise.php";
    var title=document.getElementById("title");//title of a question
    var content=document.getElementById("inputContent");//content of a question
    var checktype=document.getElementsByName("type");
    var type;//type of a question
    if(checktype[0].checked){
        type="java";
    }
    else if(checktype[1].checked){
        type="c++";
    }
    else{
        type="html";
    }
    var point=document.getElementsByTagName("select");
    var reward=point[0].value;//reward point
    url=url+"?title="+title.value;
    url=url+"?content="+content.value;
    url=url+"?type="+type;
    url=url+"?reward="+reward;
    var xmlhttp;
    if(window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
    }
    else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4&&xmlhttp.status==200){
        alert("asde");
    }
    }
    xmlhttp.open("GET",url,true);
    xmlhttp.setRequestHeader("Content-Type","utf-8");
    xmlhttp.send();
}

提高.php:

<?php
  echo "<script>alert('123')</script>";
 $title=$_GET['title'];
 $content=$_GET['content'];
 $reward=$_GET['reward'];
 $type=$_GET['type'];
?>

这让我感到困惑 alert('123'( 没有执行,但 alert("asde"( 是,我想知道为什么。我在尝试使用 php 检索这些数据时是对的......我对 ajax 不是很熟悉...请根据我的数据向我展示一些代码。谢谢。。

脚本

元素不会执行任何操作,除非它是呈现的 HTML 文档的一部分。

服务器将其返回到浏览器,然后它位于您忽略它的xmlhttp.responseText中。

(也就是说,即使您没有忽略它,您仍然可能遇到问题(。

你只是没有将响应体(JavaScript(附加到你的 DOM,请尝试:

// ...
xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState==4&&xmlhttp.status==200){
        alert("asde");
        alert(xmlHttp.responseText);
        // here you have to attach xmlHttp.responseText to your DOM
    }
}
// ...

这应该提醒你"asde",然后是"script>alert('123'(/script>">

你最好将 Jquery 与 Ajax 一起使用来发布或获取数据,而不仅仅是 Ajax。你可以看看这里jquery ajax。在这里,您将找到应该在哪里使用警报。