php根据post的数据并生成字符串

PHP接收参数是name的post请求,并输出修改后的字符串

get_new_names.php

<?php
function getIpAddr() { 
      
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) { 
        return $_SERVER['HTTP_CLIENT_IP']; 
    } 
    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { 
        return $_SERVER['HTTP_X_FORWARDED_FOR']; 
    } 
    else { 
        return $_SERVER['REMOTE_ADDR']; 
    } 
} 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = $_POST["name"];
  if (empty($name)) {
    echo "Name is empty";
  } else {
    $arr = array('Best', 'Good', 'Love', 'AI', 'Dear');
    
    //$vis_ip = getIpAddr(); 
    //array_push($vis_ip, $arr);
    
    $i = 0;
    foreach ($arr as &$value) {
        
    	echo $name.$value;
	echo '&nbsp;&nbsp;&nbsp;';
	$i = $i+1;
	if($i % 5 == 0) {echo "<br>";}
    }
    echo "<br><br>";
    $i = 0;
    foreach ($arr as &$value) {
        
    	echo $value.$name;
    	//echo "   ";
    	echo '&nbsp;&nbsp;&nbsp;';
    	$i = $i+1;
    	if($i % 5 == 0) {echo "<br>";}
    }
 }
}

?>

Javascript 调用php文件的代码:

inputobj = document.getElementById("name");
log = document.getElementById("values");
inputobj.addEventListener("input", updateValue_new);
brand_name = "";
function updateValue_new(e) {
	log.innerHTML = "";
	brand_name = e.target.value;
	if(brand_name==null)  {return;}
	else if (brand_name==undefined)  {return;}
	else if (brand_name=="")  {return;}
	get_names(brand_name);
}
function get_names(name){
	// 第一步: 创建xhr对象
	let xhr = new XMLHttpRequest();
	// 第二步: 调用open函数
	xhr.open('POST', '/get_new_names.php');
	// 第三步: 设置Content-Type属性 
	xhr.setRequestHeader('Conten-Type', 'application/x-www-form-urlencoded');
	// 第四步: 调用send()函数,同时将数据以查询字符串的形式,提交给服务器
	//console.log("2: " +name)
	// 第五步:监听onreadystatechange事件
	xhr.onreadystatechange = function() {
		if (xhr.readyState === 4 && xhr.status === 200) {
			console.log(xhr.responseText)
			log.innerHTML += xhr.responseText;
		}
	}
        //组装FormData类型的数据,重要,否则服务器端收不到传递的参数
	let formData = new FormData()
        formData.append('name', name)
	xhr.send(formData);
}

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据