【发布时间】:2020-03-21 21:43:37
【问题描述】:
与发送 json 对象相比,我发现通过 ajax 发送纯文本(字符串)有一个小问题。
我目前正在使用此设置
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
脚本
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
和电流控制器
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
我想直接向控制器发送一个字符串,我尝试了这个脚本
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
使用这个控制器
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
但是这不起作用,输入字符串显示为 null 并且 ajax 给出了错误。我目前不知道如何解决这个问题,也不知道是什么导致了错误。如果有人能指出我正确的方向,我将不胜感激
【问题讨论】:
-
该字符串应该在 sql 查询中使用,但我将在实际获取字符串后处理该问题。
标签: c# json ajax asp.net-mvc model-view-controller