【问题标题】:How do I transfer values as variables using xmlhttprequest?如何使用 xmlhttprequest 将值作为变量传输?
【发布时间】:2014-02-16 21:37:28
【问题描述】:

首先,我不是程序员,对此相对缺乏经验……我正在尝试在我的网站上使用星级评分系统,我从this 链接下载了脚本。当我在浏览器中预览它们时,它们会正确显示在我的网站上,但是当您单击星号对它们进行评分时,它并没有在我的数据库中记录该评分。使用萤火虫我想我已经追踪到通过ajax请求传输数据onclick的javascript函数。当我单击星号时,我在 firebug 中得到的响应是“您不应该尝试以这种方式访问​​此文件”。如果我注释掉 if/die 语句,我在 firebug 中得到的响应是未定义的索引,它列出了“item”、“rating”、“classes”。我下载的脚本的原始 ajax 请求代码在底部代码示例中。我到处都读过关于如何使用 xmlhttprequest 提到的 ajax 请求,所以我希望通过切换到它可以消除这个问题,但它没有。我现在没有任何语法错误,所以我认为我的 xml 请求格式正确。大家怎么看?提前谢谢你。

function RateItem(varItemId, varRate)
{
var varOrigClassName = document.getElementById(varItemId).className;
var request;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  request=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  request=new ActiveXObject("Microsoft.XMLHTTP");
  }
request.open("POST","ajax.rate.item.php",true);
//request.onload= ReloadRating;
request.setRequestHeader('item','varItemId');
request.setRequestHeader('rating','varRate');
request.setRequestHeader('classes','varOrigClassName');
request.send('item','rating','classes');
}

ajax.rate.item.php 文件

<?php
  require_once("classes/include.all.php");

  // Check that the data was sent
  if (sizeof($_POST) == 0
    || $_POST['item'] == null
    || strlen(trim($_POST['item'])) == 0
    || $_POST['rating'] == null
    || strlen(trim($_POST['rating'])) == 0
    || is_numeric($_POST['rating'])
    || $_POST['classes'] == null
    || strlen(trim($_POST['classes'])) == 0)
 {
    die("You shouldn't be attempting to access this file in this manner.");
  }

  echo Rating::RateItem($_POST['item'],$_POST['rating'],$_POST['classes']);

?>

原始的ajax请求

function RateItem(varItemId, varRating)
{
  var varOrigClassName = document.getElementById(varItemId).className;

  // Retrieve Ajax Feeds
  new Ajax.Request('ajax.rate.item.php',
    {
      method: 'post',
      parameters: {item: varItemId, rating: varRating, classes: varOrigClassName},
      onSuccess: ReloadRating,
      onFailure: RatingError
    }
  );
}

【问题讨论】:

    标签: javascript php ajax xmlhttprequest


    【解决方案1】:

    要使用 POST 方法发送参数,您可以尝试这种方式:

    xmlhttp.open("POST","ajax.rate.item.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("item=" + varItemI + "&rating=" + varRate + "&classes=" + varOrigClassName);
    

    Source MDN

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 2013-12-27
      • 2020-10-03
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多