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

时间:2017-01-08 20:17:54

标签: javascript php jquery ajax

我正在尝试将此{j}函数中的topic变量传递给我的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; 
}

faqs.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);

?>

4 个答案:

答案 0 :(得分:1)

在javascript中将主题插入为GET变量

$.getJSON("faqs.php?topic=sometopic", function(data) {

然后在PHP中读取GET变量

if(isset($_GET['topic'])){

答案 1 :(得分:0)

$.getJSON发出GET请求,而$.ajax是发送服务器并与服务器通信的主要组件。这是一个粗略的代码,可以做到这一点。

$.ajax({
    url: 'faqs.php', 
    type: 'POST',
    dataType: 'json',
    data: { topic: topics }, // topics is your topics varaible from the JS scope
    success: 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"));
        });
    },
    error: function(xhr) {
        console.log('error :(');
    }
});

答案 2 :(得分:0)

你可以通过url发送它的代码xmlhttp.open("GET", "phpFile.php?q=" + str, true); xmlhttp.send();  其中q是变量,用于访问特定变量的值,在本例中为str,在php文件中

答案 3 :(得分:0)

如果你想使用POST:

$.post('test.php', { name: "Anna" }, function(response) {
// Do something with the request, data is JSON object.
}, 'json');

并在POST变量中读取test.php。

$_POST['name'] // Anna