【问题标题】:Passing html URL parameter to PHP script将 html URL 参数传递给 PHP 脚本
【发布时间】:2019-07-07 06:34:20
【问题描述】:

这是我使用 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');
    });
});

test.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。

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

【问题讨论】:

  • 您还必须将survey_id 传递给test.php 页面。
  • @Refilon 是的,这就是我要问的问题。
  • 您调用 test.php 的唯一参数是 increase - 所以您当然不能期望 $_GET['survey_id'] 在其中有任何值。您在 HTML 页面上运行的 JS 代码必须读取此值,并将其传递...
  • 所以你的问题归结为stackoverflow.com/questions/979975/… 的另一个重复然后......?

标签: php jquery html ajax .htaccess


【解决方案1】:

在这样的数据中传递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');
        });
    });

【讨论】:

  • 如果只有 1 个参数,这可能会起作用,但如果survey_id 后面有更多参数,则会失败。
  • 这成功了!非常感谢。 RE 什么@Refilon 指出,我只有一个参数
猜你喜欢
  • 2016-07-11
  • 2022-11-21
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 2015-05-19
相关资源
最近更新 更多