用于Ajax响应的PHP文件出错

时间:2016-07-21 03:33:00

标签: php ajax

我找到了这个有用的例子:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
这展示了如何使用Ajax处理数据。但是,本文没有详细说明PHP文件应该包含什么以使示例实际工作。

我试过这个:

<?php
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
echo json_encode($computedString);
?>

其变化无济于事。结果是一个消息框,显示未定义。该示例的PHP文件中应该包含哪些内容才能使其正常工作?

以下是HTML页面,包含JS:

<label>Your name: 
  <input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
  Make a request
</span>

<script type="text/javascript">
(function() {
  var httpRequest;
  document.getElementById("ajaxButton").onclick = function()
  {
	var userName = document.getElementById("ajaxTextbox").value;
	makeRequest('test.php',userName);
  };

  function makeRequest(url, userName)
  {
    httpRequest = new XMLHttpRequest();

    if (!httpRequest)
	{
      alert('Giving up - cannot create an XMLHTTP instance.');
      return false;
    }
    httpRequest.onreadystatechange = alertContents;
	httpRequest.open('POST', url);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send('userName=' + encodeURIComponent(userName));
  }

  function alertContents()
  {
    if (httpRequest.readyState === XMLHttpRequest.DONE)
	{
      if (httpRequest.status === 200)
	  {
        //alert(httpRequest.responseText);
		try
		{
			var response = JSON.parse(httpRequest.responseText);
		}
		catch(e)
		{
			console.log(e.message + " in " + httpRequest.responseText);
			return;
		}
		alert(response.computedString);
      }
	  else
	  {
        alert('There was a problem with the request.');
      }
    }
  }
})();
</script>

编辑:
alertContents()函数修改如下:

  function alertContents()
  {
    if (httpRequest.readyState === XMLHttpRequest.DONE)
	{
      if (httpRequest.status === 200)
	  {
        //alert(httpRequest.responseText);
		console.log(response);
		console.log(httpRequest.responseText);
		var response = "default message";
		try
		{
			response = JSON.parse(httpRequest.responseText);
		}
		catch(e)
		{
			console.log(e.message + " in " + httpRequest.responseText);
			
			return;
		}
		alert(response.computedString);
      }
	  else
	  {
        alert('There was a problem with the request.');
      }
    }
  }

第一个console.log行是脚本中的第44行。重新运行程序并在控制台中查看以下内容: enter image description here

console.log(response);

被注释掉这是结果: enter image description here

另一个编辑:
这个问题确实出现在PHP脚本中。这是更新的PHP脚本和结果:

$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['computedString' => $computedString];
echo json_encode($array);

enter image description here

进一步改进:

$array = ['userData' => $name, 'computedString' => $computedString];

导致: enter image description here

1 个答案:

答案 0 :(得分:1)

<强>更新

根据我对您的评论的理解,看起来您的PHP文件没有返回JSON响应。它会返回您从表单中传递的文本。所以你的responseText是简单的字符串。

因此,当您尝试读取它的属性时,它是未定义的。立即尝试以下代码。

export class Header extends React.Component {

  componentDidMount () {

  }

  render () {
    return (
      <div className={s.root}>
        <div className={s.container}>
          <Navigation className={s.nav} />
          <Link className={s.brand} to="/">
            <Limage>
              <g id="golf">
                <path fill="none" stroke="#fff" strokeWidth="4" strokeLinejoin="round" strokeMiterlimit="10" d="M26.007885,46.7037048 c0,0-10.666666-20.6913586,2.6666679-28.8888893c0,0-11.6543217-0.2962971-14.5185194-10.8148155 c0,0-2.3703699,4.4938269,2.5185194,10.0740738C16.6745529,17.0740738,10.6992435,31.1481476,26.007885,46.7037048z"/>
                <path fill="none" stroke="#fff" strokeWidth="4" strokeLinejoin="round" strokeMiterlimit="10" d="M15.7856636,33.9629631 l-1.4814816-5.6296291c0,0-6.0740747,7.3580227-4.1481485,18.666666C10.1560335,47,10.4029474,39.0493813,15.7856636,33.9629631z" />
                <path fill="none" stroke="#fff" strokeWidth="4" strokeLinejoin="round" strokeMiterlimit="10" d="M14.1560335,7L36,1l3,4 l-0.0000038,0.000001c-1.1943779,0.5971899-2.6368942,0.3631015-3.5811348-0.5811381L33,2"/>
                <circle fill="none" stroke="#fff" strokeWidth="4" strokeLinejoin="round" strokeMiterlimit="10" cx="26" cy="10" r="4"/>
                <line fill="none" stroke="#fff" strokeWidth="4" strokeLinejoin="round" strokeMiterlimit="10" x1="17" y1="45" x2="17" y2="48"/>
                <circle fill="none" stroke="#fff" strokeWidth="4" strokeLinejoin="round" strokeMiterlimit="10" cx="17" cy="43" r="4"/>
              </g>
            </Limage>
            <span className={s.brandTxt}>tacos_cubed</span>
          </Link>
          <div className={s.banner}>
            <h1 className={s.bannerTitle}>React</h1>
            <p className={s.bannerDesc}>Complex web apps made easy</p>
          </div>
        </div>
      </div>
    )
  }

}

<强>原始 您的代码中的变量范围存在问题。

function alertContents()
  {
    if (httpRequest.readyState === XMLHttpRequest.DONE)
    {
      if (httpRequest.status === 200)
      {
          if(httpRequest.responseText == '')
           {
                alert('Error in code');
                return;
           }
        alert(httpRequest.responseText);

      }
      else
      {
        alert('There was a problem with the request.');
      }
    }
  }

在这里,您将响应定义为尝试块中的变量,然后尝试在块外部警告。这就是 undefined 的原因。

您应该在 TRY 块内移动警告声明,或在外部定义变量。

var response = JSON.parse(httpRequest.responseText);