首页 > 解决方案 > 将 html URL 参数传递给 PHP 脚本

问题描述

这是我使用 php 的第一周,所以提前感谢您的建设性回复。

我有一个附加了 url 参数的 html 页面:mywebsite.com/f.html?survey_id=5d86055f35bf41f3a35f2c779fc478dc

我需要将这个survey_id 参数传递给一个将这个id 保存在一个文本文件中的php 脚本。由于文本文件为空,我当前的代码未正确传递。

html页面是/f.html php脚本是/test.php

这一切都在服务器端运行。

保存脚本可以正常工作,就好像我只是保存了一个像'd'这样的字符串而不是$id,一切正常。

我已经使用 $_GET 尝试了下面的代码,但输出为空,所以我假设参数没有传递给执行 fwrite 的 .php 脚本。

我还读到这可以通过修改 .htaccess 文件来解决,并尝试将以下内容添加到我的 .htaccess 文件中,但它没有解决问题。

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

我觉得这不是完全正确的规则,但不知道如何修改它以适应我的特殊情况。

jQuery(document).on('click', 'div#download', function () {
    jQuery('div#counter1').html('Loading...');
    var ajax = jQuery.ajax({
        method: 'get',
        url: '/test.php', // Link to this page
        data: { 'increase': '1' }
    });
    ajax.done(function (data) {
        jQuery('div#counter1').html(data);
    });
    ajax.fail(function (data) {
        alert('ajax fail : url of ajax request is not reachable');
    });
});

测试.php

  $myFile = "testFile2.txt";
  $fh = fopen($myFile, 'w') or die("can't open file");
  $id = $_GET['survey_id'];
  $stringData = $id;
  fwrite($fh, $stringData);
  fclose($fh);

文本文件中的预期结果应该是 5d86055f35bf41f3a35f2c779fc478dc。

当前结果是文本文件为空。

标签: phpjqueryhtmlajax.htaccess

解决方案


在这样的数据中传递survey_id

 jQuery(document).on('click', 'div#download', function () {
var url =window.location.search;
    var survey_id = /survey_id =([^&]+)/.exec(url)[1];


        jQuery('div#counter1').html('Loading...');
        var ajax = jQuery.ajax({
            method: 'get',
            url: '/test.php', // Link to this page
            data: { 'increase': '1', 'survey_id': survey_id }
        });
        ajax.done(function (data) {
            jQuery('div#counter1').html(data);
        });
        ajax.fail(function (data) {
            alert('ajax fail : url of ajax request is not reachable');
        });
    });

推荐阅读