如何使用输入类型文本

时间:2017-03-04 10:33:22

标签: javascript jquery html input

我使用api new york times搜索引擎,我的问题很简单,我只想在我的网址中使用输入类型文本更改参数。 我怎样才能做到这一点 ? 结束日期和排序是参数之一,我只想知道如何用html中的输入字段更改字符串。 这里是我的代码的副本:

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel='stylesheet' type="text/css" href="nyt.css">
    <link rel='stylesheet' type="text/css" href="font.css">
    <link rel='stylesheet' type="text/css" href="grille.css">
</head>
<body>
    <div class='container'>
       <button type="submit" id='searchButton'></button>
       <input type="text" id='searchTerm' placeholder="search">
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src='nyt.js'></script>
</body>
</html>

js:

var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
var searchTerm = document.getElementById('searchButton');
url += '?' + $.param({
  'api-key': "[API KEY]",
  'end_date': "19440606",
  'sort': "newest"
});
$.ajax({
  url: url,
  method: 'GET',
  q: searchTerm,
}).done(function(result) {
  console.log(result);
}).fail(function(err) {
  throw err;
});

2 个答案:

答案 0 :(得分:0)

您可以使用“value”属性获取输入字段的值,如下所示:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        //BindingContext = this;

        string[] courses =
        {
            "ADO.NET  By Example",
            "Xamarin.Android",
            "Xamarin.iOS",
            "Xamarin.Forms",
            "JAVA EE: Java Server Pages",
            "JAVA EE: Programming Servlets"
        };

        lstView.ItemsSource = courses;

        lstView.ItemSelected += async (sender, e) =>
        {
            if (e.SelectedItem == null)
            {
                // don't do anything if we just de-selected the row
                return;
            }
            else
            {
                if (e.SelectedItem.ToString() == "ADO.NET  By Example")
                {
                    await Navigation.PushAsync(new Project1()); /// It throws an error here saying I need to use a Navigation Page.
                }
            }
        };   
    }
  }

另请参阅:JavaScript: how to get value of text input field?

答案 1 :(得分:0)

function sendRequest(searchTerm) {
  var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
  url += '?' + $.param({
    'api-key': "[API KEY]",
    'end_date': "19440606",
    'sort': "newest"
  });
  console.log(searchTerm);
  return $.ajax({
    url: url,
    method: 'GET',
    q: searchTerm,
  });
}

document.querySelector('#searchButton').addEventListener('click', function(e){
  e.preventDefault();
  var query = document.querySelector('#searchTerm').value.trim();

  if (query.length > 0) {
    sendRequest(query)
      .done(function(result) {
        console.log(result);
      }).fail(function(err) {
        throw err;
      });
  }
})