我正在尝试将我的 topic
变量从这个 javascript 函数传递到我的 php 文件 faqs.php。我知道您可以使用表单来执行此操作,但是当单击 html 页面上的文本时会调用此函数。我尝试过 AJAX,但它对我不起作用,我觉得必须有一种更简单的方法。
getFaqs函数:
function getFaqs(topicId, topic) {
$("#topic-container").html("");
//insert javascript to send 'topic' to php file here
$.getJSON("faqs.php", function(data) {
if(data == "") {
$("<div>", {class: "list-group-item", text: "Please add FAQs."}).appendTo($("#topic-container"));
}
$.each(data, function(faqId, faq){
$("<div>", {id: "faq" + faqId, class: "list-group-item", text: faq}).appendTo($("#topic-container"));
});
});
return false;
}
常见问题解答.php:
<?php
header('Content-Type: application/json; charset=utf-8');
//insert some php to get 'topic' here
if(isset($_POST['topic'])){
$topic=$_POST['topic'];
$clean_topic = preg_replace('/\s+/', '', $topic);
}else{
echo json_encode("Please enter a topic!");
}
$musicalinstruments = array("Question1"=>"What is the best musical instrument in the world?", "Answer1"=>"The English concertina", "Question2"=>"How many double bass players does it take to change a light bulb?", "Answer2"=>"None, the piano player can do that with his left hand");
$programminglanguages = array("Question"=>"Why do programmers confuse halloween and christmas?", "Answer"=>"Because Oct 31 = Dec 25");
$varietiesofpizza = array("Question"=>"Should I eat more pizza?", "Answer"=>"Yes. Always.");
echo json_encode ($topic);
?>
最佳答案
在 JavaScript 中将主题作为 GET 变量插入
$.getJSON("faqs.php?topic=sometopic", function(data) {
然后在 PHP 中读取 GET 变量
if(isset($_GET['topic'])){
关于javascript - 如何在没有表单的情况下从javascript获取变量到php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41537405/