访问获取数据并在同一页面上发布数据

时间:2016-10-18 08:57:53

标签: php ajax post get

我是相当新的发布和获取等等,但我正在努力学习它,现在我有这个问题。我正在使用PHP从文本文件中收集数据,通过带有Ajax的URL将其发送到Javascript。所以这是在没有页面刷新(和工作)的情况下完成的。但是在同一页面上,我也在单击单选按钮(也提交表单)时使用Javascript发布表单数据,以某种方式可以访问(例如保存在数据库中或回显到页面)。因为页面在提交表单时刷新,我认为它不应该是这样的问题吗?

到目前为止,我只是尝试添加下面的代码来发布,但它不起作用,因为只要我向文档添加更多PHP代码,页面崩溃(变为空白)。我想echo部分由于PHP代码中的先前echo而无效,但我该如何解决呢?

我还可以补充一点,我尝试在下面添加此代码段之前的PHP代码需要以die结束才能使页面正常运行。所以我很难知道在哪里以及如何放置更多的PHP代码。

表单数据的提交似乎有效,因为单击单选按钮会刷新页面。

<?php
    if ( isset($_POST['image'])
    {
        $image = $_POST[ 'image' ]; // 'image' is the name of the radio buttons
        echo "$image<br>";
        //Will result in "image1" or "image2", etc - whatever "value" you assigned to the radio buttons
    }
?>

<script>
$(document).ready(function(){
    // Bind to change event for all radio buttons
    $('input[type="radio"]').on('change', function() {
        // Submit the form ("this" refers to the radio button)
        $(this).closest('form').submit();
    });
});
</script>

这是我想要添加内容以访问已发布表单数据的PHP代码。

<?php
    if ( isset($_GET['firstItem']) && isset($_GET['numItems']) )
    {
        $firstItem = $_GET['firstItem'];
        $numItems = $_GET['numItems'];

        $subtestNumber = 7;
        $filename = sprintf("subtests/%d.txt", $subtestNumber);

        $fileHandle = fopen($filename, "rt");

        for ($numLinesToSkip=0; $numLinesToSkip<$firstItem; $numLinesToSkip++)
            fgets($fileHandle);

        $results = array();
        for ($itemCount=0; $itemCount<$numItems; $itemCount++)
        {
            $curLine = fgets($fileHandle);
            $curLine = trim($curLine);
            array_push($results, $curLine);
        }
        fclose($fileHandle);

        echo json_encode($results);
        die;   // stop execution now - dont output the html below

    }
?>

0 个答案:

没有答案
相关问题