javascript - 如何在没有表单的情况下从javascript获取变量到php?

标签 javascript php jquery ajax

我正在尝试将我的 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/

相关文章:

javascript - 如何保持 float div 在窗口调整大小时居中 (jQuery/CSS)

javascript - Bootstrap 表显示空行

javascript - 继承类的原型(prototype)对象如何等于 JavaScript 中原始类的新实例?

php - 更改页面标题 - 确定当前页面是什么

php获取数组的数据大小

javascript - 无法让 jQuery CDN 为 WordPress 插件工作

javascript - 使用 javaScript 将前缀表达式转换为中缀表达式

php - 在 php 中使用 "Add To Cart"链接运行 SQL 命令

具有动态加载图像的 jQuery galleria 插件

javascript - 如何单击链接(菜单)打开选项卡?